VBA中Range和Cells的速度

概述

RangeCells這兩個函數,都可以獲取單元格內容和將內容寫入單元格。既然這兩個功能相同,那麼速度就成爲了選擇的關鍵。

注:Range有着比Cells更強大的功能,大家千萬不要把這兩個函數完全等同。當然了,這也從側面反應了速度上必然Range更慢。

測試速度的代碼

Private Declare Function QueryPerformanceCounter Lib "KERNEL32" (lpPerformanceCount As Currency) As Long
Private Declare Function QueryPerformanceFrequency Lib "KERNEL32" (lpFrequency As Currency) As Long

Private m_Frequency   As Currency
Private m_Start       As Currency
Private m_Now         As Currency
Private m_Available   As Boolean

Sub test()

m_Available = (QueryPerformanceFrequency(m_Frequency) <> 0)
If Not m_Available Then
Debug.Print "Performance Counter not available"
End If

Dim i As Long
Dim a As String

Cells.NumberFormatLocal = "@"
For i = 1 To 100000 Step 1
    Cells(i, 1) = CStr(i)
Next i

QueryPerformanceCounter m_Start

For i = 1 To 100000 Step 1
    ' 下面四句中選一句執行
    a = Range("A" & CStr(i)) ' Range read
    a = Cells(i, 1)          ' Cells read
    Cells(i, 1) = a          ' Cells write
    Range("A" & CStr(i)) = a ' Range write
Next i

QueryPerformanceCounter m_Now

Elapsed = 1000 * (m_Now - m_Start) / m_Frequency
Debug.Print Format(Elapsed, "#.0000")
End Sub

測試結果

測試結果的時間單位是毫秒。

第幾次測試 Range read Cells read Range write Cells write
1 1019.9720 344.1759 6220.0159 5105.3813
2 1020.0355 346.0292 6216.2530 5103.4524
3 1020.8382 345.4371 6207.0230 5079.1922
4 1023.1144 344.1790 6198.1607 5090.5974
5 1018.8067 344.7482 6188.6159 5091.1590
6 1024.7189 344.8035 6181.9272 5085.4331
7 1017.7546 342.1849 6183.4536 5100.7955
8 1023.6095 344.1097 6188.9005 5074.8064
9 1015.5275 344.2437 6186.2355 5076.1584
10 1021.1321 343.7072 6187.4848 5083.3936

結論

無論讀還是寫,使用Range進行轉字符串再傳入的方式,比Cells直接傳入數值,要慢。

所以應該優先使用Cells

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章