在 Microsoft Visio Professional 2010 中,我已经隔离了我遇到的这个小代码片段的错误。页面上有一个包含 2 个形状的容器,我想在另一个循环中遍历这些形状。但我不断收到无效参数错误。
我对解决方案的尝试是顶部块,但它仅适用于内部循环的相同定义。在外循环的第二次迭代期间,似乎有些东西正在发生变化,但我不确定。我觉得这与定义 For Each 循环的方式有关。
Sub Nested_Loop_Error()
Dim a As Variant
Dim b As Variant
Dim lngs() As Long
'This Works
lngs = ActiveDocument.Pages(1).Shapes.ItemFromID(1).ContainerProperties.GetMemberShapes(visContainerFlagsDefault)
For a = 0 To 1
For Each b In lngs
'Do nothing
Next b
Next a
'This does not work
For a = 0 To 1
For Each b In ActiveDocument.Pages(1).Shapes.ItemFromID(1).ContainerProperties.GetMemberShapes(visContainerFlagsDefault)
MsgBox "In Loop for a=" & a
Next b
Next a
End Sub
编辑:我一直在玩它并让它工作,但我真正感兴趣的是它为什么工作。当 a=1 时,第二个代码块失败,在 docMyDoc.Pages... 行中给出无效参数
以下代码显示了使用变体或文档变量在循环中定义 ActiveDocument 的区别。使用调试器,我看不出 docMyDoc 或 varMyDoc 的定义方式有何不同。
Sub Nested_Loop_Error2()
Dim a As Variant
Dim b As Variant
Dim docMyDoc As Visio.Document
Dim varMyDoc As Variant
'This works
For a = 0 To 1
Set varMyDoc = ActiveDocument
For Each b In varMyDoc.Pages(1).Shapes.ItemFromID(1).ContainerProperties.GetMemberShapes(visContainerFlagsDefault)
MsgBox "Using variant, a=" & a
Next b
Next a
'This does not work
For a = 0 To 1
Set docMyDoc = ActiveDocument
For Each b In docMyDoc.Pages(1).Shapes.ItemFromID(1).ContainerProperties.GetMemberShapes(visContainerFlagsDefault)
MsgBox "Using document, a=" & a
Next b
Next a
End Sub