Excel VBAで処理を高速化する定番テクニックが 「配列に読み込んで一括処理」+「自動範囲検出」 です。Cells を組み合わせることで、柔軟かつ効率的にデータを扱えます。
基本の考え方
- Range/Cells から配列に読み込む
- 一度にメモリに取り込むことで、セルを1つずつ操作するより圧倒的に高速化。
- 配列内で処理する
- ループや計算は配列上で行う。
- 結果をまとめて書き戻す
- 最後に一括でセルに反映。
自動範囲の検出
Dim lastRow As Long, lastCol As Long
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
VB- 最終行 →
Cells(Rows.Count, 列).End(xlUp).Row - 最終列 →
Cells(行, Columns.Count).End(xlToLeft).Column
配列に読み込む
Dim data As Variant
data = Range(Cells(1, 1), Cells(lastRow, lastCol)).Value
VBRange(...).Valueを配列に代入すると 2次元配列 になる。data(行, 列)でアクセス可能。
配列で処理する(例:数値を2倍)
Dim i As Long, j As Long
For i = 1 To UBound(data, 1)
For j = 1 To UBound(data, 2)
If IsNumeric(data(i, j)) Then
data(i, j) = data(i, j) * 2
End If
Next j
Next i
VB結果を一括で書き戻す
Range(Cells(1, 1), Cells(lastRow, lastCol)).Value = data
VB- 配列をそのままセル範囲に代入できる。
- 一括書き込みで高速化。
応用例:自動範囲+配列処理
Sub FastProcess()
Dim lastRow As Long, lastCol As Long
Dim data As Variant
Dim i As Long, j As Long
' 自動範囲検出
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
' 配列に読み込み
data = Range(Cells(1, 1), Cells(lastRow, lastCol)).Value
' 配列処理(例:文字列に「_done」を付加)
For i = 1 To UBound(data, 1)
For j = 1 To UBound(data, 2)
If VarType(data(i, j)) = vbString Then
data(i, j) = data(i, j) & "_done"
End If
Next j
Next i
' 一括書き戻し
Range(Cells(1, 1), Cells(lastRow, lastCol)).Value = data
End Sub
VB実務での使い分けポイント
- 大量データ処理 → 配列必須(1セルずつ操作は遅い)
- 範囲が可変 → 自動範囲検出
- 処理後は一括書き戻し → 高速化の鍵
- Cells × 配列 × 自動範囲 → 最強コンビ
💡 この入門を押さえれば、Excel VBAでの 数万行データ処理も一瞬で終わるようになります。
