首页 > 解决方案 > VISIO VBA 获取组中所有形状的集合

问题描述

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

这是我的代码:

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

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

标签: vbams-officevisio

解决方案


您的问题从这一行开始:

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

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

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

这里发生的情况是()VBA 评估subshp并返回默认方法返回的任何内容(例如名称或 ID)。因此,您不会将 a 添加Shape到您的收藏中,而是添加其他内容(例如 aStringLong)。

这一行中的空格让我感到困惑:

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

你的 VBE 应该这样写:

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

所以这告诉我那里正在发生其他事情。但是,此时代码中的对象subshp是一个Shape对象,因此不应引起任何问题。

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

            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 shp之前的下一行End If

最后一点,一个好主意是不要将变量(例如“形状”)命名为与现有的公共方法或属性相同的名称——这可能会导致对您使用的参数产生一些混淆。


推荐阅读