Excel VBA | 列ループ × Offset × Resize の複合応用編テンプレ集

VBA
スポンサーリンク

ここでは For Each × Offset × Resize を組み合わせて「列単位で隣列やブロックを動的に処理する」応用パターンをまとめます。
単純な隣列操作から一歩進んで、複数列をまとめて加工・抽出・拡張する黄金テンプレです。


応用パターン 10選

1. 各列の右隣に合計行を追加

Dim col As Range, lastRow As Long
For Each col In Range("A:D").Columns
    lastRow = Cells(Rows.Count, col.Column).End(xlUp).Row
    col.Resize(lastRow, 1).Offset(0, 1).Cells(lastRow, 1).Value = WorksheetFunction.Sum(col.Resize(lastRow, 1))
Next col
VB

👉 各列の最終行の右隣に合計を出力。


2. 各列の右隣に平均値を縦方向に展開

Dim col As Range
For Each col In Range("A:D").Columns
    col.Resize(col.Rows.Count, 1).Offset(0, 1).Value = WorksheetFunction.Average(col)
Next col
VB

👉 各列の右隣に平均値を全行へ展開。


3. 各列の右隣に最大値をヘッダ下へ

Dim col As Range
For Each col In Range("A:D").Columns
    col.Cells(2, 1).Offset(0, 1).Value = WorksheetFunction.Max(col)
Next col
VB

👉 各列の最大値をヘッダ下(2行目)に出力。


4. 各列の右隣に「件数」をまとめて出力

Dim col As Range
For Each col In Range("A:D").Columns
    col.Cells(2, 1).Offset(0, 1).Value = WorksheetFunction.Count(col)
Next col
VB

👉 各列の件数を右隣に出力。


5. 各列の右隣に「異常値件数」を出力

Dim col As Range, cell As Range, cnt As Long
For Each col In Range("A:D").Columns
    cnt = 0
    For Each cell In col.Resize(20, 1).Cells
        If IsNumeric(cell.Value) And cell.Value < 0 Then cnt = cnt + 1
    Next cell
    col.Cells(2, 1).Offset(0, 1).Value = cnt
Next col
VB

👉 各列の負の値件数を右隣に出力。


6. 各列の右隣に「補助列」を生成

Dim col As Range
For Each col In Range("A:D").Columns
    col.Resize(col.Rows.Count, 1).Offset(0, 1).Value = "補助_" & col.Column
Next col
VB

👉 各列の右隣に補助列を生成。


7. 各列の右隣に「累積値」を展開

Dim col As Range, cell As Range, sumVal As Double
For Each col In Range("A:D").Columns
    sumVal = 0
    For Each cell In col.Resize(20, 1).Cells
        sumVal = sumVal + cell.Value
        cell.Offset(0, 1).Value = sumVal
    Next cell
Next col
VB

👉 各列の右隣に累積値を展開。


8. 各列の右隣に「差分」を出力

Dim col As Range, cell As Range
For Each col In Range("A:D").Columns
    For Each cell In col.Resize(20, 1).Cells
        If cell.Row > 2 Then
            cell.Offset(0, 1).Value = cell.Value - cell.Offset(-1, 0).Value
        End If
    Next cell
Next col
VB

👉 各列の右隣に前行との差分を出力。


9. 各列の右隣に「判定結果」を出力

Dim col As Range, cell As Range
For Each col In Range("A:D").Columns
    For Each cell In col.Resize(20, 1).Cells
        cell.Offset(0, 1).Value = (cell.Value >= 100)
    Next cell
Next col
VB

👉 各列の右隣に TRUE/FALSE 判定を出力。


10. 各列の右隣に「タグ」を一括付与

Dim col As Range
For Each col In Range("A:D").Columns
    col.Resize(col.Rows.Count, 1).Offset(0, 1).Value = "TAG_" & col.Column
Next col
VB

👉 各列の右隣にタグを付与。


✅ まとめ

  • For Each col In Range(…).Columns → 列単位でループ
  • Offset → 隣列に結果を出力
  • Resize → 列範囲を拡張して一括処理
  • 応用編 → 合計・平均・最大/最小・件数・異常値・累積・差分・判定・タグ付与

💡 この「列ループ × Offset × Resize 複合応用編」をベースにすれば、売上表・勤怠表・在庫表などの 業務別ライブラリ に直結できます。

タイトルとURLをコピーしました