1

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.

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?

2
  • What is the value of labelCounter when it falls over? Have you got Option Base set to 1? Commented Feb 5, 2015 at 22:29
  • Where is the code residing inside the userform or in a separate module. If the latter don't use Me use the actual form name Commented Feb 5, 2015 at 22:38

2 Answers 2

5
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
Sign up to request clarification or add additional context in comments.

Comments

0

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 ReDim it once you reach a point in the code execution where you know how many elements are in it. I think you can also ReDim Preserve to change the size of the array without deleting its contents.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.