How do I declare an array variable in VBA?

后端 未结 7 676
灰色年华
灰色年华 2020-12-08 20:02

I need to add the var in array

Public Sub Testprog()

Dim test As Variant
Dim iCounter As Integer

If test = Empty Then
    iCounter = 0
    test(iCounter) =         


        
7条回答
  •  独厮守ぢ
    2020-12-08 20:37

    As pointed out by others, your problem is that you have not declared an array

    Below I've tried to recreate your program so that it works as you intended. I tried to leave as much as possible as it was (such as leaving your array as a variant)

    Public Sub Testprog()
        '"test()" is an array, "test" is not
        Dim test() As Variant
        'I am assuming that iCounter is the array size
        Dim iCounter As Integer
    
        '"On Error Resume Next" just makes us skip over a section that throws the error
        On Error Resume Next
    
        'if test() has not been assigned a UBound or LBound yet, calling either will throw an error
        '   without an LBound and UBound an array won't hold anything (we will assign them later)
    
        'Array size can be determined by (UBound(test) - LBound(test)) + 1
        If (UBound(test) - LBound(test)) + 1 > 0 Then
            iCounter = (UBound(test) - LBound(test)) + 1
    
            'So that we don't run the code that deals with UBound(test) throwing an error
            Exit Sub
        End If
    
        'All the code below here will run if UBound(test)/LBound(test) threw an error
        iCounter = 0
    
        'This makes LBound(test) = 0
        '   and UBound(test) = iCounter where iCounter is 0
        '   Which gives us one element at test(0)
        ReDim Preserve test(0 To iCounter)
    
        test(iCounter) = "test"
    End Sub
    

提交回复
热议问题