深耕 Visio 二次開發多年,整理九大高頻問題與解決方案,涵蓋屬性值轉換、Cell 讀寫、存在性判斷、ShapeData 行號取得、圖形存在性檢查、UI 客製化、Name/NameU 差異、巨集錄製除錯等實戰技巧。
Visio 儲存字串時會用雙雙引號包裹(如 ""Value""),讀寫需雙向轉換:
// 讀取:移除外層引號,雙引號還原單引號
public static string FormulaStringToString(string formula) {
if (formula.StartsWith("\"") && formula.EndsWith("\"")) {
formula = formula.Substring(1, formula.Length - 2);
formula = formula.Replace("\"\"", "\"");
}
return formula;
}
// 寫入:單引號轉雙引號並包裹
public static string StringToFormulaForString(string input) {
if (input == null) return null;
string result = input.Replace("\"", "\"\"");
return "\"" + result + "\"";
}
使用 get_ResultStr(visNoCast) 可直接取得下拉選單的顯示文字,而非內部索引:
public static string GetShapeCellValue(Shape shape, string cellName) {
const string PREFIX = "Prop.";
if (shape.get_CellExistsU(PREFIX + cellName, (short)VisExistsFlags.visExistsAnywhere) != 0) {
return FormulaStringToString(
shape.get_CellsU(PREFIX + cellName).get_ResultStr(VisUnitCodes.visNoCast));
}
return string.Empty;
}
public static bool SetShapeCellValue(Shape shape, string cellName, string value) {
const string PREFIX = "Prop.";
if (shape.get_CellExistsU(PREFIX + cellName, (short)VisExistsFlags.visExistsAnywhere) != 0) {
shape.get_CellsU(PREFIX + cellName + ".Value").Formula = StringToFormulaForString(value);
return true;
}
return false;
}
public static bool ShapeCellExist(Shape shape, string cellName) {
const string PREFIX = "Prop.";
return shape.get_CellExistsU(PREFIX + cellName, (short)VisExistsFlags.visExistsAnywhere) != 0;
}
public static int GetCustomPropRow(Shape shape, string propName) {
const string PREFIX = "Prop.";
if (shape.get_CellExistsU(PREFIX + propName, (short)VisExistsFlags.visExistsAnywhere) != 0) {
return shape.get_CellsRowIndexU(PREFIX + propName);
}
return -1;
}
public static bool HasShapeInWindow(Window window) {
try {
window.SelectAll();
bool result = window.Selection.Count > 0;
window.DeselectAll();
return result;
} catch { return false; }
}
// 隱藏形狀搜尋窗 (Visio 2007+)
VisApplication.Settings.ShowShapeSearchPane = false;
// 停用自動連接
VisApplication.Settings.EnableAutoConnect = false;
// 設定模具背景色
VisApplication.Settings.StencilBackgroundColor = 10070188;
NameU 為唯一識別名稱,跨語系環境穩定;Name 可能因語系不同而相同卻對應不同物件,開發時優先使用 NameU。
對於陌生操作或屬性,開啟 Visio 巨集錄製器,手動操作一次,產出 VBA 程式碼即可快速掌握對應 API。