How to reduce runtime for code using ranges and string comparisons

后端 未结 3 2014
礼貌的吻别
礼貌的吻别 2020-12-10 22:45

I have the following code and it does exactly what I need it to do however, the loop takes far too long to run (3 minutes +). I am new to VBA so I am not exactly sure 1) wha

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 23:21

    Accessing a sheet within a loop is very slow. A better approach is to copy the data into a Variant, array loop over the array and then copy the results back to the sheet

    Something like this:

    Sub Demo()
        Dim i As Long
        Dim datCol3 As Variant
        Dim datCol14 As Variant
    
        With Sheets("Sheet1")
            ' Copy data into a Variant Array
            datCol3 = .Range(.Cells(1, 3), .Cells(13000, 3)).Formula
            datCol14 = .Range(.Cells(1, 14), .Cells(13000, 14)).Value
            ' Loop over the array
            For i = 2 To 13000
                If datCol3(i, 1) = "Police" And datCol14(i, 1) = "Bi-wkly Uniform Pay" Then
                    datCol3(i, 1) = "Police - Uniform"
                End If
            Next
            'Return the results to the sheet
            .Range(.Cells(1, 3), .Cells(13000, 3)).Formula = datCol3
        End With
    End Sub
    

提交回复
热议问题