gpt4 book ai didi

excel - ActiveCell.Offset() 和 Range() 之间的速度差异?

转载 作者:行者123 更新时间:2023-12-04 21:13:08 24 4
gpt4 key购买 nike

摘要:我遍历多行数据,每次通过循环将来自不同列的数据存储在大约 6 个不同的变量中

问题:我会使用 Range("A" & some iterator) 节省大量的 CPU 周期吗?而不是 ActiveCell.Offset(some number) ?一个比另一个快多少?

提前致谢!

最佳答案

出于纯粹的无聊和一点好奇,我为各种方法组合了一个粗略的计时器来循环 100,000 个 Excel 单元格。

理想情况下,您应该每次运行多次并取平均值,但它会给您一个粗略的速度轮廓。

在我的机器上,这就是我得到的

enter image description here

Option Explicit

#If Win64 Then
Public Declare PtrSafe Function GetTickCount Lib "kernel32" () As Long
#Else
Public Declare Function GetTickCount Lib "kernel32" () As Long
#End If

Sub TestSpeedofReadingCells()
Dim tcStart As Long
Dim tcEnd As Long
Dim temp As Variant

Dim i As Long
Dim rngobject As Range
Dim rngItem As Range
Dim rngArray() As Variant
Const rowsToRead As Long = 100000


'***Read individual cells using .Range
With Sheet1
tcStart = GetTickCount
For i = 1 To rowsToRead
temp = .Range("A" & i).Value
Next i
tcEnd = GetTickCount
Debug.Print "Time1: " & tcEnd - tcStart
End With

'***Read individual cells using .Range & screenupdating off
With Sheet1
Application.ScreenUpdating = False
tcStart = GetTickCount
For i = 1 To rowsToRead
temp = .Range("A" & i).Value
Next i
tcEnd = GetTickCount
Application.ScreenUpdating = True
Debug.Print "Time1a: " & tcEnd - tcStart
End With

'***Read individual cells using .Range & screenupdating off & using value2
With Sheet1
Application.ScreenUpdating = False
tcStart = GetTickCount
For i = 1 To rowsToRead
temp = .Range("A" & i).Value2
Next i
tcEnd = GetTickCount
Application.ScreenUpdating = True
Debug.Print "Time1b: " & tcEnd - tcStart
End With

'***Read individual cells using range object
With Sheet1
Set rngobject = .Range("A1:A" & rowsToRead)
tcStart = GetTickCount
For Each rngItem In rngobject
temp = rngItem
Next rngItem
tcEnd = GetTickCount
Debug.Print "Time2: " & tcEnd - tcStart
End With

'***Read individual cells using activecell
With Sheet1
tcStart = GetTickCount
.Range("A1").Select
For i = 1 To rowsToRead
temp = ActiveCell.Offset(i - 1, 0).Value
Next i
tcEnd = GetTickCount
Debug.Print "Time3: " & tcEnd - tcStart
End With

'***Read individual cells using activecell & screenupdating off
With Sheet1
Application.ScreenUpdating = False
tcStart = GetTickCount
.Range("A1").Select
For i = 1 To rowsToRead
temp = ActiveCell.Offset(i - 1, 0).Value
Next i
tcEnd = GetTickCount
Application.ScreenUpdating = True
Debug.Print "Time3a: " & tcEnd - tcStart
End With

'***Read individual cells using array
With Sheet1
tcStart = GetTickCount
rngArray = .Range("A1:A" & rowsToRead).Value
For i = 1 To rowsToRead 'should really use Lbound to Ubound but only example
temp = rngArray(i, 1)
Next i
tcEnd = GetTickCount
Debug.Print "Time4: " & tcEnd - tcStart
End With

End Sub

关于excel - ActiveCell.Offset() 和 Range() 之间的速度差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12183493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com