擦除后实例化动态数组

时间:2019-03-29 09:28:58

标签: vba dynamic-arrays visio

我正在尝试在擦除动态数组后实例化它。 我使用数组来存储创建的形状,因此不需要循环页面上的每个形状。既然已经有很多。每个新页面都会擦除数组,但在尝试将第一个形状添加到数组时遇到“下标超出范围”错误。

Dim SeqShapes() As Shape
For PageCount = 0 to activeDocument.Pages.Count
    Erase SeqShapes

    For ShapesNeeded = 0 to ShapesCount
        Set NewShape = ActivePage.Drop(SomeShape, 20, 20)
        SeqShapes(UBound(SeqShapes)) = NewShape
    Next

    'Some more code

Next

这将返回错误,因为数组中没有条目。 我不想使用固定的数组,因为无法知道要预先创建多少个形状。

我尝试添加一个虚拟记录,但似乎无法弄清楚语法:

Dim SeqShapes() As Shape
Dim DummyShape As Shape
For PageCount = 0 to activeDocument.Pages.Count
    Erase SeqShapes
    SeqShapes(0) = DummyShape

    For ShapesNeeded = 0 to ShapesCount
        Set NewShape = ActivePage.Drop(SomeShape, 20, 20)
        SeqShapes(UBound(SeqShapes)) = NewShape
    Next

    'Some more code

Next

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

使用集合而不是数组

 Dim SeqShapes As Collection
 For PageCount = 0 to activeDocument.Pages.Count
    Set SeqShapes = Nothing      '  Easiest way to clear it is to recreate it.
    Set SeqShapes = New Collection

    Dim ShapesNeeded
    Dim newShape As Shape
    For ShapesNeeded = 0 To 3
        Set newShape = ActivePage.Drop(SomeShape, 20, 20)
        SeqShapes.Add newShape     ' Add the shape into Collection
    Next ShapesNeeded  
    ...
Next PageCount

要遍历集合中的所有形状:

    ' Using ForEach (you have to declare you running variable as Variant)
    Dim sh As Variant
    For Each sh In SeqShapes
        Debug.Print sh.Name
    Next sh

    ' Using for
    Dim i As Long
    For i = 1 To SeqShapes.Count
        Debug.Print SeqShapes(i).Name
    Next i