0

I am trying to get my macro to run a bit faster and i was wondering which way is the fastest:

1)

Set cell2 = Range("F" & CurrentRow)
Set Columns = Range(cell2, cell2.Offset(0, LastColumn - 6))
i = 0
For Each cell In Columns
If cell.Value = " - " Then
Else
    ...code...
Next cell

2)

Set cell2 = Range("F" & CurrentRow)
CurrentColumn=6
While CurrentColumn <= LastColumn
     Cells(CurrentColumn,CurrentRow).Value...code...
     CurrentColumn = CurrentColumn+1
Wend

And is there a faster way than these two?

Thanks in advance, Bruno

4

2 回答 2

2

循环遍历范围的最快方法是将其转储到变体中并循环遍历。从 VBA 对 Excel 的每次调用都会很昂贵(尽管只有在大数据时才值得注意),并且循环遍历一个变体非常快。

示例代码

Sub test()

Dim data As Variant
Dim i As Long, j As Long

'Example range
data = Range("A1:Z100").Value

For i = LBound(data, 1) To UBound(data, 1)
    For j = LBound(data, 2) To UBound(data, 2)
        If data(i, j) = " - " Then
            'Do something
        End If
    Next
Next

End Sub
于 2013-05-16T04:14:55.633 回答
1

要加速更新大量单元格中的值的 VBA 代码,最好的办法是在代码之前添加以下行:

Application.ScreenUpdating = False

然后是你的代码;最后

Application.ScreenUpdating = True

你会惊讶于你的代码运行速度有多快。另外,宏运行时屏幕不会闪烁。

于 2013-05-16T04:06:33.717 回答