Populating VBA dynamic arrays

前端 未结 5 1115
悲哀的现实
悲哀的现实 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 13:56

    As Cody and Brett mentioned, you could reduce VBA slowdown with sensible use of Redim Preserve. Brett suggested Mod to do this.

    You can also use a user defined Type and Sub to do this. Consider my code below:

    Public Type dsIntArrayType
       eElems() As Integer
       eSize As Integer
    End Type
    
    Public Sub PushBackIntArray( _
        ByRef dsIntArray As dsIntArrayType, _
        ByVal intValue As Integer)
    
        With dsIntArray
        If UBound(.eElems) < (.eSize + 1) Then
            ReDim Preserve .eElems(.eSize * 2 + 1)
        End If
        .eSize = .eSize + 1
        .eElems(.eSize) = intValue
        End With
    
    End Sub
    

    This calls ReDim Preserve only when the size has doubled. The member variable eSize keeps track of the actual data size of eElems. This approach has helped me improve performance when final array length is not known until run time.

    Hope this helps others too.

提交回复
热议问题