2012年1月12日 星期四

For-Each與For-Next何者較快?

如果二者都可以達到相同的目的,則For-Each陳述句似乎會比較快!
Sub test_For_each()
    Dim RowNum As Long, ColNum As Long, time1 As Double
    Dim c As Range, i As Long
   
    Cells.Clear
    RowNum = InputBox("幾列?")
    i = 0
    time1 = Timer
   
    For Each c In Range("A1").Resize(RowNum, 1)
        i = i + 1
        c.Value = i
    Next c
   
    MsgBox Format(Timer - time1, "0.00") & " secs."
   
End Sub

==================================================================
Sub test_For_next()
    Dim RowNum As Long, ColNum As Long, time1 As Double
    Dim c As Range, i As Long, j As Long, k As Long
   
    Cells.Clear
    RowNum = InputBox("幾列?")
    k = 0
    time1 = Timer
   
    For i = 1 To RowNum
            k = k + 1
            Range("A1").Offset(i - 1, 0).Value = k
    Next i
   
    MsgBox Format(Timer - time1, "0.00") & " secs."
   
End Sub

沒有留言:

張貼留言