动态数组的麻烦

时间:2014-06-13 18:23:36

标签: vba excel-vba dynamic-arrays excel

作为VBA的诺言,我有一段时间了解阵列,特定的动态数组如何工作。我是一名工业工程专业的学生,​​所以我的大部分编码都是用MatLab完成的。

我的问题是:为什么我不断获得以下代码的运行时错误'9'“下标超出范围”:

Sub FunWithArrays()

Dim DynArray()
Dim i As Integer
Dim j As Integer
j = 1


For i = 1 To 10

    DynArray(j) = i
    j = j + 1
    ReDim DynArray(UBound(DynArray) + 1)
    MsgBox DynArray(i)

Next

End Sub

感谢任何和所有帮助!

1 个答案:

答案 0 :(得分:1)

正如评论中提到的那样,动态数组只是:动态。也就是说,如果你声明一个没有维度的数组,就像你在Dim DynArray()那样,那么它此时没有任何"槽"存储任何东西。

当一个数组以这种方式声明时,你需要Redim它来告诉它你想要它有多少个插槽(大概是在从其他一些数据或用户输入确定之后)。

完整的代码是:

Sub FunWithArrays()

    Dim DynArray()
    Dim i As Integer
    Dim j As Integer
    j = 1

    Redim DynArray(10) 
    ' redimensioned the array to hold 10 items (since 
    ' you've set the loop as i=1 to 10 you must already 
    ' know that the array wants to hold 10 things)

    For i = 1 To 10

        'ReDim Preserve DynArray(i) 
        ' this is how you could do it if you didn't know in 
        ' advance that you were going to loop 10 times, 
        ' but as somebody else said, this is a slow way to do it. 

        DynArray(i) = j
        j = j + 1
        MsgBox DynArray(i)
        ' Generally instead of a messagebox here I would use:
        ' Debug.Print DynArray(i)
        ' this then prints out the value (on a new line each time) 
        ' into the immediate window which means you can see the 
        ' output without having to click "OK" each time.

    Next

End Sub

您还可以在循环内或稍后重新定义数组以保存不同数量的项目,但如果您想保留已存储在数组中的项目,则必须使用ReDim

ReDim Preserve DynArray(i)

声明数组类型通常也是一种很好的做法。当您使用Dim DynArray()时,这会创建一个类型Variant的数组,它可以包含任何内容(String,Double,Object等)。如果您明确声明类型,例如Dim DynArray() as Integer然后它只分配足够的内存来保存整数,这样效率更高。对于许多应用程序而言,速度的差异并没有什么区别,但是当你处理数千次循环时,它就很重要。