Search code examples
loopsms-accessvariablesvba

VBA Access declare variables names using loop


How do I declare variable names in a loop? For example I need to declare Combo1Count, Combo2Count, Combo3Count, and so on :

Dim i As Integer
For i = 1 To 6
    Dim Combo & i & Count as Integer
Next i

Then later on I will need to refer to these variables eg:

For i = 1 To 6
    If Combo & i & Count > 0 ....
Next i

Solution

  • Scope is not the issue in VBA. The issue is ... that you can't.

    A work-around is using Select Case:

    Dim i As Integer
    For i = 1 To 6
        Select Case 1
            Dim Combo1 As Integer
        Select Case 2
            Dim Combo2 As Integer
        ' ....
        Select Case 6
            Dim Combo6 As Integer
        End Select
    Next i
    

    which, of course, doesn't make sense. So use:

    Dim Combo1 As Integer
    Dim Combo2 As Integer
    ' ....
    Dim Combo6 As Integer