書中第11章提到,將資料逐一寫入儲存格範圍是非常消耗時間的,建議改用陣列變數將數值寫入儲存格範圍。
以下以傳統方式跑100*100的範圍,花了3.18秒。
Sub LoopFillRange()Dim cellsDown As Long, cellsAcross As IntegerDim CurrRow As Long, CurrCol As IntegerDim StartTime As DoubleDim CurrVal As LongCells.ClearcellsDown = Val(InputBox("How many cells down?"))cellsAcross = Val(InputBox("How many cells across?"))StartTime = TimerCurrVal = 1Application.ScreenUpdating = FalseFor CurrRow = 1 To cellsDownFor CurrCol = 1 To cellsAcrossActiveCell.Offset(CurrRow - 1, CurrCol - 1).Value = CurrValCurrVal = CurrVal + 1Next CurrColNext CurrRowApplication.ScreenUpdating = TrueMsgBox Format(Timer - StartTime, "00.00") & "秒"End Sub
以下以陣列變數的模式,跑100*100的儲存格僅花了 0.05秒。
重點在於我用橘色框起來的 theRange.Value = tmpArray 這段敘述。
Sub ArrayFillRange()Dim cellsDown As Long, cellsAcross As LongDim i As Long, j As LongDim CurrRow As Long, CurrCol As IntegerDim StartTime As DoubleDim CurrVal As LongDim tmpArray() As LongDim theRange As RangeCells.ClearcellsDown = Val(InputBox("How many cells down?"))cellsAcross = Val(InputBox("How many cells across?"))StartTime = TimerReDim tmpArray(1 To cellsDown, 1 To cellsAcross)Set theRange = ActiveCell.Range(Cells(1, 1), Cells(cellsDown, cellsAcross))CurrVal = 0Application.ScreenUpdating = FalseFor i = 1 To cellsDownFor j = 1 To cellsAcrosstmpArray(i, j) = CurrVal + 1CurrVal = CurrVal + 1Next jNext itheRange.Value = tmpArrayApplication.ScreenUpdating = TrueMsgBox Format(Timer - StartTime, "00.00") & "秒"End Sub
沒有留言:
張貼留言