excel 我的VBA代码在运行时非常慢

kzmpq1sx  于 2023-02-25  发布在  其他
关注(0)|答案(2)|浏览(274)

基本上,我想遍历H列(430行),如果它的值是“Tera”,那么我想将E列(即第6列)中单元格的值更改为F列(第7列)中的值。

Sub R_Adj()
Sheets("Sheet5").Select
temp = 7
For Each i In Worksheets("Sheet5").Range("H8:H430").Cells
temp = temp + 1
Set column_to = Worksheets("Sheet5").Cells(temp, 6)
Set column_from = Worksheets("Sheet5").Cells(temp, 7)
If i.Value = "Tera" Then column_to.Value = column_from.Value
Next
End Sub

运行时间大约是10秒,这在我看来对于这样一个简单的算法来说太长了。有人有什么建议来提高这段代码的性能和运行时间吗?

h43kikqp

h43kikqp1#

使用数组。

Option Explicit
Sub RTB_justering()

    Dim rng As Range, ar, i As Long, n As Long
    With Sheets("Sheet5")
        Set rng = .Range("E8:H430")
        ar = rng.Value2
        For i = 1 To UBound(ar)
            If ar(i, 4) = "Tera" Then 'H
                ar(i, 1) = ar(i, 2) ' F->E
                n = n + 1
            End If
        Next
        rng.Value2 = ar
    End With
    MsgBox n & " cells changed", vbInformation
    
End Sub
p5fdfcr1

p5fdfcr12#

也许以下方法可以稍微提高运行时间:

Sub RTB_justering()
    Dim sh5 As Worksheet
    Dim rng As Range
    Set sh5 = Worksheets("Sheets5")
    sh5.Select
    For Each rng In sh5.Range("H8:H430")
        If rng.Value2 = "Tera" Then
            '    value2 in Column E <-- value2 in Column F
            rng.Offset(0, -3).Value2 = rng.Offset(0, -2).Value2
        End If
    Next
End Sub

相关问题