下标超出范围,Excel VBA,尝试在循环中创建数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28355224/
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
Subscript out of range, Excel VBA, Trying to create an array within a loop
提问by kraimecj
I'm trying to loop through all the controls in my form and for each time it catches a Label, the Tag element of the Label is added into the array.
我正在尝试遍历表单中的所有控件,并且每次捕获一个标签时,都会将 Label 的 Tag 元素添加到数组中。
Dim labelCounter As Integer
labelCounter = 0
Dim arrayTag() As String
For Each ctl In Me.Controls
Select Case TypeName(ctl)
Case "Label"
arrayTag(labelCounter) = ctl.Tag
labelCounter = labelCounter + 1
End Select
Next
I keep getting the Subscript out of range error. What's going wrong here?
我不断收到下标超出范围错误。这里出了什么问题?
回答by Tim Williams
Sub Tester()
Dim labelCounter As Integer
Dim arrayTag() As String
Dim ct As String, ctl
labelCounter = 0
ReDim arrayTag(0 To labelCounter)
For Each ctl In Me.Controls
ct = TypeName(ctl)
If ct = "Label" Then
If labelCounter > 0 Then
ReDim Preserve arrayTag(0 To labelCounter)
End If
arrayTag(labelCounter) = ctl.Tag
labelCounter = labelCounter + 1
End If
Next
'Debug.Print Join(arrayTag, ",")
End Sub
回答by Acantud
I think your only issue is you created an array (arrayTag) without specifying how many elements are in it. As far as I recall, when creating an array you need to either A.) Specify the number of elements in it, or B.) Create an array the way you did (With empty parenthesis) and then ReDimit once you reach a point in the code execution where you know how many elements are in it. I think you can also ReDim Preserveto change the size of the array without deleting its contents.
我认为您唯一的问题是您创建了一个数组(arrayTag)而没有指定其中有多少个元素。据我所知,在创建数组时,您需要 A.) 指定其中的元素数,或 B.) 按照您所做的方式创建一个数组(带空括号),然后ReDim在到达某个点时您知道其中有多少元素的代码执行。我认为您也可以ReDim Preserve在不删除其内容的情况下更改数组的大小。
Dim labelCounter As Integer
labelCounter = 0
Dim arrayTag(50) As String
For Each ctl In Me.Controls
Select Case TypeName(ctl)
Case "Label"
arrayTag(labelCounter) = ctl.Tag
labelCounter = labelCounter + 1
End Select
Next

