gpt4 book ai didi

vba - 在 VBA (excel) 中循环行的最有效/最快的方法是什么?

转载 作者:行者123 更新时间:2023-12-01 16:55:36 27 4
gpt4 key购买 nike

我知道 Excel 中的 VBA 并不是最快的方法 - 但我需要最有效(即最快)的方法来循环遍历大量行样本。

目前我有:

For Each c In Range("$A$2:$A$" & Cells(Rows.count, "A").End(xlUp).row
' do stuff
Next c

“做一些事情”包括在这里和那里插入一行(所以我需要保持范围的动态查找。)

有什么想法(查看 10,000 行以上)吗?

编辑我已经在使用了

Application.ScreenUpdating = False
Application.Calculation = xlManual

最佳答案

如果您只是循环遍历 A 列中的 10k 行,则将该行转储到变体数组中,然后循环遍历该数组。

然后,您可以将元素添加到新数组(同时在需要时添加行)并使用 Transpose() 将数组一次性放入您的范围内,或者您可以使用迭代器变量来跟踪您所在的行并以这种方式添加行。

Dim i As Long
Dim varray As Variant

varray = Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row).Value

For i = 1 To UBound(varray, 1)
' do stuff to varray(i, 1)
Next

以下示例说明了如何在评估每个单元格后添加行。此示例只是在 A 列中包含单词“foo”的每一行之后插入一行。由于我们从 A2 开始,因此在插入过程中“+2”不会添加到变量 i 中。如果我们以 A1 开始数组,那么它会是 +1。

Sub test()

Dim varray As Variant
Dim i As Long

varray = Range("A2:A10").Value

'must step back or it'll be infinite loop
For i = UBound(varray, 1) To LBound(varray, 1) Step -1
'do your logic and evaluation here
If varray(i, 1) = "foo" Then
'not how to offset the i variable
Range("A" & i + 2).EntireRow.Insert
End If
Next

End Sub

关于vba - 在 VBA (excel) 中循环行的最有效/最快的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8178161/

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