Excel VBA | 列ループ(For Each × Offset)黄金パターン集

VBA
スポンサーリンク

ここでは For Each × Offset を組み合わせて「列単位で隣列や補助列へ処理を展開する」パターンをまとめます。
Resize を使わず、あえて Offset で「隣列操作」に特化した黄金テンプレです。


基本パターン 10選

1. 各列の右隣に合計を出力

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

👉 各列の合計を右隣のセルに出力。


2. 各列の左隣に平均を出力

Dim col As Range
For Each col In Range("B:E").Columns
    col.Cells(1, 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(1, 1).Offset(0, col.Columns.Count).Value = WorksheetFunction.Count(col)
Next col
VB

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


4. 各列の右隣に最大値を出力

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

👉 各列の最大値を右隣に出力。


5. 各列の右隣に最小値を出力

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

👉 各列の最小値を右隣に出力。


6. 各列の右隣に「列番号」を記録

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

👉 各列の右隣に列番号を記録。


7. 各列の右隣に「ヘッダ名」をコピー

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

👉 各列のヘッダを右隣にコピー。


8. 各列の右隣に「データ型判定」を出力

Dim col As Range
For Each col In Range("A:D").Columns
    If WorksheetFunction.Count(col) = col.Cells.Count Then
        col.Cells(1, 1).Offset(0, col.Columns.Count).Value = "数値列"
    Else
        col.Cells(1, 1).Offset(0, col.Columns.Count).Value = "文字列列"
    End If
Next col
VB

👉 各列の右隣に「数値列/文字列列」を判定して出力。


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

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.Cells
        If IsNumeric(cell.Value) And cell.Value < 0 Then cnt = cnt + 1
    Next cell
    col.Cells(1, 1).Offset(0, col.Columns.Count).Value = cnt
Next col
VB

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


10. 各列の右隣に「補助タグ」を付与

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

👉 各列の右隣に「補助タグ」を付与。


✅ まとめ

  • For Each col In Range(…).Columns → 列単位でループ
  • Offset → 隣列に結果を出力(右隣・左隣)
  • WorksheetFunction → 集計・判定を簡単に実装
  • 黄金パターン → 合計・平均・最大/最小・件数・型判定・異常値検出

💡 この「列ループ × Offset 黄金パターン集」をベースに、さらに Resize を組み合わせれば「複数列まとめ処理」や「ブロック単位の列操作」に発展できます。

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