Really slow For loop

2019-09-18 16:38发布

How can I set my loop faster?

I have 4 columns and more than 250 rows and it takes like 5 minutes to loop this:

Application.Calculation = xlCalculationManual
Call CPU0

Dim TableA As Range:    Set TableA = Range("L_PriceA")

With TableA
LongA = TableA.Rows.Count
    For s = 1 To LongA
       .Cells(s, 3).Value = "dynamic"
       .Cells(s, 4).Value = "dynamic"
       .Cells(s, 5).Value = "dynamic"
       .Cells(s, 6).Value = "dynamic"
    Next
End With

"dynamic" will be data from xml because nobody helped me with THIS and I don't know :/. Also looked at some loop problems here in stackO, but no main boost.

1条回答
劳资没心,怎么记你
2楼-- · 2019-09-18 17:17

Looping over a range is slow. Avoid it by moving your data to Variant Array, something like this:

Dim dat As Variant
Dim s As Long

With TableA
    LongA = .Rows.Count
    dat = .Value  ' TableA must be at least 6 columns wide
    For s = 1 To LongA
       dat(s, 3) = "dynamic"
       dat(s, 4) = "dynamic"
       dat(s, 5) = "dynamic"
       dat(s, 6) = "dynamic"
    Next
    TableA.Value = dat
End With
查看更多
登录 后发表回答