How can I optimize this vba loop code?

前端 未结 1 1447
一个人的身影
一个人的身影 2021-01-25 00:34

Hi I wrote this code. but this code is very slow. How can I optimize this code?

Private Sub printItem(r, lastCol, objStream)
    FirstCol = 1

    Dim strFirst A         


        
相关标签:
1条回答
  • 2021-01-25 01:06

    This is the likely reason why your code is slow: you are looping through cells. There is significant overhead to each communication between VBA and Excel sheet data, and this adds up when you refer to many cells one at a time.

    Instead, you should load all your data at once into a Variant array, and then loop through that array, as shown below. This is significantly faster.

        Dim varData As Variant
    
        varData = ActiveSheet.Cells(r, FirstCol).Resize(1, lastCol - FirstCol + 1)
    
        For c = LBound(varData, 2) To UBound(varData, 2)
    
            data = CStr(varData(1, c))
    
            If LenB(Trim$(data)) > 0 Then
                ' etc.
            EndIf
    
        Next c
    

    For further reading, have a look at this old but still relevant article: http://www.avdf.com/apr98/art_ot003.html

    0 讨论(0)
提交回复
热议问题