VISIO VBA 获取一组中所有形状的集合

VISIO VBA Get a collection of all Shapes in a group

我想获取某个组中所有形状的集合。组中的形状可能本身就是一个组,所以我(认为我)需要一个递归函数来获取每个形状。

这是我的代码:

Function getAllShapes(shp As Shape) As Collection
    Dim shapes As Collection
    Dim subshp As Shape
    Dim colShp As Shape
    Dim col As Collection

    If shp.Type = 2 Then 'Check if shp is a group
        For Each subshp In shp.shapes
            shapes.Add (subshp) 'Add the subshp to the shape collection
            If subshp.Type = 2 Then 'Check if subshp is group
                Set col = getAllShapes (subshp) 'Get all the shapes from the group
                For Each colShp In col 'Error here
                    shapes.Add (colShp) 'Add all the shapes to the collection
                Next colShp
            End If
        Next subshp
    Else: shapes.Add (shp)
    End If

    Set getAllShapes = shapes
    Set shapes = Nothing

End Function

但是,每当我尝试从函数访问集合时(例如在函数本身中),我总是会收到运行时错误:需要对象

您的问题从这一行开始:

        shapes.Add (subshp) 'Add the subshp to the shape collection

应该是(注意删除括号):

        shapes.Add subshp 'Add the subshp to the shape collection

这里发生的事情是 () 意味着 VBA 计算 subshp 并且 return 无论默认方法 return 是什么(例如姓名或身份证)。因此,您不是在 collection 中添加 Shape,而是添加其他内容(例如 StringLong)。

这一行的space让我很困惑:

Set col = getAllShapes (subshp) 'Get all the shapes from the group

你的 VBE 应该这样写:

Set col = getAllShapes(subshp) 'Get all the shapes from the group

所以这告诉我那里发生了其他事情。但是,此时代码中的 subshpShape object,因此不应引起任何问题。

所以现在,当您使用以下代码时,VBA 正在寻找 Shape 但您的 collection 包含其他内容。这会导致代码行不匹配 - 因此您的错误。

            For Each colShp In col 'Error here
                shapes.Add (colShp) 'Add all the shapes to the collection
            Next colShp

你多久做一次?

  • shapes.Add (subshp) 'Add the subshp to the shape collection
  • shapes.Add (colShp) 'Add all the shapes to the collection
  • Else: shapes.Add (shp)

此外:无需将两行与“:”连接在一起 - 这有助于混淆您的代码。 他们应该是:

  • shapes.Add subshp 'Add the subshp to the shape collection
  • shapes.Add colShp 'Add all the shapes to the collection
  • Elseshapes.Add shpEnd If
  • 之前的下一行

最后一点,一个好主意是不要将变量(例如 'shapes')命名为与现有通用方法或 属性 相同的名称 - 这可能会导致对哪个参数的混淆您正在使用。