擦除后实例化动态数组

问题描述 投票:1回答:1

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

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

任何帮助将不胜感激。

vba dynamic-arrays visio
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.