Excel VBA - How to Redim a 2D array?

前端 未结 9 2138
闹比i
闹比i 2020-11-30 06:57

In Excel via Visual Basic, I am iterating through a CSV file of invoices that is loaded into Excel. The invoices are in a determinable pattern by client.

I am readin

9条回答
  •  一整个雨季
    2020-11-30 07:32

    here is updated code of the redim preseve method with variabel declaration, hope @Control Freak is fine with it:)

    Option explicit
    'redim preserve both dimensions for a multidimension array *ONLY
    Public Function ReDimPreserve(aArrayToPreserve As Variant, nNewFirstUBound As Variant, nNewLastUBound As Variant) As Variant
        Dim nFirst As Long
        Dim nLast As Long
        Dim nOldFirstUBound As Long
        Dim nOldLastUBound As Long
    
        ReDimPreserve = False
        'check if its in array first
        If IsArray(aArrayToPreserve) Then
            'create new array
            ReDim aPreservedArray(nNewFirstUBound, nNewLastUBound)
            'get old lBound/uBound
            nOldFirstUBound = UBound(aArrayToPreserve, 1)
            nOldLastUBound = UBound(aArrayToPreserve, 2)
            'loop through first
            For nFirst = LBound(aArrayToPreserve, 1) To nNewFirstUBound
                For nLast = LBound(aArrayToPreserve, 2) To nNewLastUBound
                    'if its in range, then append to new array the same way
                    If nOldFirstUBound >= nFirst And nOldLastUBound >= nLast Then
                        aPreservedArray(nFirst, nLast) = aArrayToPreserve(nFirst, nLast)
                    End If
                Next
            Next
            'return the array redimmed
            If IsArray(aPreservedArray) Then ReDimPreserve = aPreservedArray
        End If
    End Function
    

提交回复
热议问题