Range() VS Cells() - run times

后端 未结 3 784
一生所求
一生所求 2020-12-03 11:12

I see a lot of VBA code on this site using the Range method with For loops:

Range(\"A\" & i)

As opposed to a

3条回答
  •  忘掉有多难
    2020-12-03 12:00

    I expanded upon the testing after seeing an example of .Cells(1, "A") notation which I thought might be a good balance between the readability of .Range("A1") with the speed of .Cells(1, 1)

    I tested reads and writes and found for reads, .Cells(1, "A") executed in about 69% of the time .Range("A1") and .Cells(1, 1) executed in half the time of .Range("A1"). For writes there was a smaller difference (~88% and 82% respectively).

    Code:

    Option Explicit
    Sub test()
    Dim i, x, y, a, t1, t2, t3, t4
    x=1000000
    y=x/100
    Debug.Print "---Read---" 'Cell A1 contains the number 55
    t1=Timer*1000
    For i = 1 to x
        a = Sheet1.Range("A1")
    Next
    t2=Timer*1000
    Debug.Print t2 - t1 & "ms"
    For i = 1 to x
        a = Sheet1.Cells(1, "A")
    Next
    t3=Timer*1000
    Debug.Print t3 - t2 & "ms (" & Round(100*(t3-t2)/(t2-t1),1)&"%)"
    For i = 1 to x
        a = Sheet1.Cells(1, "A")
    Next
    t4=Timer*1000
    Debug.Print t4 - t3 & "ms (" & Round(100*(t4-t3)/(t2-t1),1)&"%)"
    Debug.Print "---Write---"    
    a=55
    t1=Timer*1000
    For i = 1 to y
        Sheet1.Range("A1") = a
    Next
    t2=Timer*1000
    Debug.Print t2 - t1 & "ms"
    For i = 1 to y
        Sheet1.Cells(1, "A") = a
    Next
    t3=Timer*1000
    Debug.Print t3 - t2 & "ms (" & Round(100*(t3-t2)/(t2-t1),1)&"%)"
    For i = 1 to y
        Sheet1.Cells(1, "A") = a
    Next
    t4=Timer*1000
    Debug.Print t4 - t3 & "ms (" & Round(100*(t4-t3)/(t2-t1),1)&"%)"
    Debug.Print "----"
    End Sub
    

    ^transcribed by hand, may contain typos...

    Platform:
    Excel 2013 32 bit
    Windows 7 64 bit
    16GB Ram
    Xeon E5-1650 v2 @3.5GHz

    (edit: changed "x" to "y" in write section of code-see disclaimer on hand-typed code!)

提交回复
热议问题