将值分配给动态数组元素会导致下标超出范围错误
Sub ArrTest()
Dim Arr() As Variant
Arr(1, 1) = "Test"
End Sub
我没有对数组进行维度,因为我不知道需要什么大小是。我将最终将这个数组写入一个电子表格。我试图将将来写入的单元格的左上角分配为test。
I did not dimension the array as I do not know what size it will need to be. I will eventually be writing this array to a spreadsheet. I was attempting to assign the upper left hand corner of the cells that would be written in the future as "test".
现在,如果我明白动态数组开始索引在0,所以第一个元素是真的Arr(0,0)。我试过Arr(0,0)并得到相同的错误。
Now if I understand correctly dynamic arrays start to index at 0, so the first element is really Arr(0,0). I tried Arr(0,0) and got the same error.
我想真正的问题是:
如何为未定义的动态数组的元素分配一个值?
How to assign a value to an element of an undefined dynamic array?
你必须将数组变暗你使用它之前的大小。这很简单:
You'll have to dim the array to a size before you use it. This is pretty simple though:
Sub ArrTest()
Dim Arr() As Variant
redim Arr(0 to 1, 0 to 1)
Arr(1, 1) = "Test"
redim preserve Arr(0 to 2, 0 to 1)
Arr(2, 1) = "Test2"
End Sub
redim
方法将重新定义您的数组。使用关键字 Preserve
将确保在重新定标期间存储在数组中的数据不会丢失。
The redim
method will redimension your array. Using the keyword Preserve
will insure that the data stored in the array is not lost during the redimensioning.