vba 公共动态数组返回错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1311217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Public Dynamic Array returns error
提问by Yoga
Hello all I am getting an error
大家好,我收到一个错误
Run-time error '9':
Subscript out of range
with the following code
使用以下代码
Public newarray() As String
Sub test1()
Dim int1 As Integer
int1 = 0
Do
int1 = int1 + 1
newarray(int1) = int1 * 5
Loop Until int1 > 3
End Sub
when i decare the array
当我 decare 数组
Public newarray(4) As string
it works, however I wish to declare a dynamic array. Please help. Thank you.
它有效,但是我希望声明一个动态数组。请帮忙。谢谢你。
回答by awe
You can allocate the array size by using ReDim
:
您可以使用ReDim
以下方法分配数组大小:
Public newarray() As String
Sub test1()
Dim int1 As Integer
ReDim newarray(4)
int1 = 0
Do
int1 = int1 + 1
newarray(int1) = int1 * 5
Loop Until int1 > 3
End Sub
This will redefine your entire array. If you need to preserve the contents of the array, and just change the size, you can use ReDim Preserve newarray(4)
.
这将重新定义您的整个数组。如果您需要保留数组的内容,而只是更改大小,则可以使用ReDim Preserve newarray(4)
.
Your code assumes that arrays are 1 based. This can be 0 based (set by option in VB). To be sure your code works regardless of this option, you should use LBound
/UBound
for the limits of your counter:
您的代码假定数组是基于 1 的。这可以是基于 0 的(由 VB 中的选项设置)。为确保无论此选项如何,您的代码都能正常工作,您应该使用LBound
/UBound
作为计数器的限制:
int1 = LBound(newarray)
Do
newarray(int1) = int1 * 5
int1 = int1 + 1
Loop Until int1 > UBound(newarray)