如何在 Visio 中使用 VBA 获取形状数据?

How to get Shape Data with VBA in Visio?

我已经为我的问题寻找了 4 小时的解决方案,但没有找到适合我的方法。我有一个正方形并添加了一个变量 "test",其值为 "hello":

Visio Shape

现在我想读取VBA中的变量"test"。为此,我首先必须查看变​​量是否存在:

Public Sub GetShapeData()
    Dim shpsObj As Visio.Shapes
    Dim shpObj As Visio.Shape

    Set shpsObj = ActivePage.Shapes
    Set shpObj = shpsObj(1)

    Debug.Print shpObj.CellExistsU("Prop.test", 0)
End Sub

我总是得到 0 作为结果。问题出在哪里?

尝试使用 属性 ResultStr

Debug.Print shpObj.CellExistsU("Prop.test").ResultStr("")

也许这段代码可以提供帮助

If shpObj.CellExistsU("Prop.test", 0) then Debug.Print shpObj.Cells("Prop.test").ResultStr("")

如果 CellExists 或 CellExistsU returns 都不匹配,则表明您指向的形状没有该名称的形状数据行。如果是这种情况,那么您可能会发现遍历页面上的所有形状并检查每个形状包含的内容很有用。下面是一段简短的代码来帮助解决这个问题:

Public Sub ReportPageShapes()
Dim vPag As Visio.Page
Set vPag = ActivePage

Dim shp As Visio.Shape
For Each shp In vPag.Shapes
    ReportShapeData shp, 0
Next

End Sub

Private Sub ReportShapeData(ByRef shp As Visio.Shape, indent As Integer)
Dim iPropSect As Integer
iPropSect = Visio.VisSectionIndices.visSectionProp

Debug.Print String(indent, Chr(9)) & shp.NameID & " (Index = " & shp.Index & ")"

If shp.SectionExists(iPropSect, Visio.VisExistsFlags.visExistsAnywhere) <> 0 Then
    Dim i As Integer
    For i = 0 To shp.Section(iPropSect).Count - 1 Step 1
        Dim vCell As Visio.Cell
        Set vCell = shp.CellsSRC(iPropSect, i, Visio.VisCellIndices.visCustPropsValue)
        'Could also report vCell.RowName here as well if required
        Debug.Print String(indent, Chr(9)) & Chr(9) & vCell.RowNameU, vCell.ResultStr("")
    Next i
End If

If shp.Shapes.Count > 0 Then
    Dim s As Visio.Shape
    For Each s In shp.Shapes
        ReportShapeData s, indent + 1
    Next
End If

If indent = 0 Then
    Debug.Print vbCrLf
End If

End Sub

这通过对每个子项递归或调用相同的方法来遍历页面上的每个形状 + 所有子形状(因为它们也可以包含形状数据)。