Populating VBA dynamic arrays

前端 未结 5 1094
悲哀的现实
悲哀的现实 2020-12-07 13:19

The following code gives me error 9 \"subscript out of range\". I meant to declare a dynamic array so that the dimension changes as I add elements to it. Do I have to create

5条回答
  •  时光说笑
    2020-12-07 14:07

    In addition to Cody's useful comments it is worth noting that at times you won't know how big your array should be. The two options in this situation are

    1. Creating an array big enough to handle anything you think will be thrown at it
    2. Sensible use of Redim Preserve

    The code below provides an example of a routine that will dimension myArray in line with the lngSize variable, then add additional elements (equal to the initial array size) by use of a Mod test whenever the upper bound is about to be exceeded

    Option Base 1
    
    Sub ArraySample()
        Dim myArray() As String
        Dim lngCnt As Long
        Dim lngSize As Long
    
        lngSize = 10
        ReDim myArray(1 To lngSize)
    
        For lngCnt = 1 To lngSize*5
            If lngCnt Mod lngSize = 0 Then ReDim Preserve myArray(1 To UBound(myArray) + lngSize)
            myArray(lngCnt) = "I am record number " & lngCnt
        Next
    End Sub
    

提交回复
热议问题