vba - 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
但是,我总是遇到运行时错误:每当我尝试从函数访问集合时需要对象(例如在函数本身中)
解决方案
您的问题从这一行开始:
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
到您的收藏中,而是添加其他内容(例如 aString
或Long
)。
这一行中的空格让我感到困惑:
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
Else
在shapes.Add shp
之前的下一行End If
最后一点,一个好主意是不要将变量(例如“形状”)命名为与现有的公共方法或属性相同的名称——这可能会导致对您使用的参数产生一些混淆。
推荐阅读
- python - 在 Jupyter Notebook 中运行 python 语句后没有得到结果
- java - 控制改造调用的错误,如 (404)
- azure-machine-learning-service - Azure 机器学习计算配额?
- python-3.x - 有效地分组数据集,同时保留额外的列
- javascript - Javascript“选择”更改转到锚点(锚点ID是选择值)
- php - 我必须使用 Eloquent 在 Laravel 中加入 6 个不同的表格
- javascript - 根据客户组显示文本
- ios - 更改 UIImage 中的白色像素
- css - 如何在 typescript 环境中的 material-ui 按钮内渲染 react-router-dom NavLink 的 activeClassName 样式?
- google-apps-script - getRespondentEmail() 会生成脚本失败,即使它返回了回复者的电子邮件地址