更新日 2013年1月16日
2010年10月27日
Excelでは、配列をセル範囲に一括セットしたり、その逆にセル範囲のデータを一括して配列に取り込んだりできます。
ワークシートにデータをセットするとき、セルに直接入力していく方法と配列に予めセットしてから配列をセル範囲にセットする方法を比較する。
テストプログラムは下記の通りです。
VBEの標準モジュールに貼りつけて実行してみてください。
Public Sub test1()
Dim rr As Long
Dim cc As Long
Dim idx As Long
Dim aryRows As Variant
Dim tm As Variant
Dim aryRange As Variant
'セル行数の配列を作成
aryRows = Array(1000, 5000, 10000, 30000, 60000)
'ワークシート「test1」に出力します
With Worksheets("test1")
'セルに直接出力
'すべてのセル内容をクリア
.Cells.ClearContents
'イミディエイトエリアに出力します
Debug.Print "セル直接"
For idx = 0 To UBound(aryRows)
'午前0時から現在までの秒数を取得
tm = Timer
'セルに直接数値を出力します
For rr = 1 To aryRows(idx)
.Cells(rr, 1).Value = rr
Next rr
'処理時間をイミディエイトエリアに出力します
Debug.Print aryRows(idx) & "行", Timer - tm & "(秒)"
Next idx
'配列にデータをセットし、その配列をシートに出力
.Cells.ClearContents
Debug.Print "配列経由"
For idx = 0 To UBound(aryRows)
tm = Timer
'データを格納する配列を準備
'セル範囲に出力するので二次元配列が必要
'今回は、aryRows()行,1列
ReDim aryRange(0 To aryRows(idx) - 1, 0 To 0)
'配列に数値を格納します
For rr = 1 To aryRows(idx)
aryRange(rr - 1, 0) = rr
Next rr
'配列をセル範囲に出力します
.Range(.Cells(1, 1), .Cells(aryRows(idx), 1)) = aryRange
'処理時間を出力します
Debug.Print aryRows(idx) & "行", Timer - tm & "(秒)"
Next idx
End With
End Sub
実行結果は下記の通り。ただし、PCの性能により絶対値は変わってくると思いますので、両者の差のみに注目してください。