VBA Excel,形状数组。如何修复错误“索引到指定的集合是否超出界限”?

问题描述 投票:0回答:2

在Excel中我有三个形状namned ON_1ON_2ON_3。我想建立一个Shape索引数组并获得ShapeRange。我有VBA代码,但我得到一个错误,说;指定集合的​​索引超出范围。这是代码:

Sub test()

Dim sht As Worksheet
Dim shprng As ShapeRange
Dim shape_index As Variant
Dim i As Long

Set sht = ActiveSheet

ReDim shape_index(1 To sht.Shapes.Count)
For i = 1 To UBound(shape_index)
    shape_index(i) = i
Next

Set shprng = sht.Shapes.Range(shape_index)

End Sub

我期望得到变量qazxsw poi来包含数组中的所有shapenames。

但是我得到了这行代码的错误:

shprng

运行时错误1004:指定集合的​​索引超出范围

有任何想法吗?

arrays excel vba range shapes
2个回答
0
投票

试试这个 ...

Set shprng = sht.Shapes.Range(shape_index)

这条线......

Sub test()
    Dim sht As Worksheet
    Dim shprng As ShapeRange
    Dim shape_index() As Variant
    Dim i As Long

    Set sht = ActiveSheet

    ReDim shape_index(1 To sht.Shapes.Count)
    For i = 1 To UBound(shape_index)
        shape_index(i) = i
    Next

    Set shprng = sht.Shapes.Range(shape_index)
End Sub

......是你的问题。它最初并未声明为数组。

现在是这个......

Dim shape_index As Variant

0
投票

您可以使用以下修复:

  • 没有必要使用重型内存Dim shape_index() As Variant 阵列。为了你的目标,一个简单的variant阵列就足够了。
  • 检查Integer是否为.Shapes.Count,否则您的代码将无效
  • (可选)实际的数组大小可以通过0获得(即使在这种情况下它不需要因为你已经知道你的下界)

有了这些修正,它现在有效。这是代码:

UBound(shape_index) - LBound(shape_index) + 1

希望能帮助到你。

© www.soinside.com 2019 - 2024. All rights reserved.