Range と Cells を組み合わせて「最終列まで処理する」例
「最終列まで処理する」とは、横方向にどこまでデータが入っているかを自動で調べて処理することです。行方向の「最終行」と同じ考え方で、列方向にも応用できます。
基本の流れ
- 最終列を調べる
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
VBColumns.Count → Excelの最大列数(例: 16,384列 = XFD列).End(xlToLeft) → 一番右から左に向かってデータがあるセルを探すColumn → そのセルの列番号を取得
👉 この例では「1行目の最終列」を調べています。
- Range と Cells を組み合わせて処理範囲を指定
Range(Cells(1, 1), Cells(1, lastCol))
VB1行目のA列から最終列までを自動で指定できる
例1:1行目のデータをすべて2倍にして2行目へコピー
Sub 最終列までコピー()
Dim lastCol As Long
Dim i As Long
' 1行目の最終列を取得
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
' A列から最終列まで処理
For i = 1 To lastCol
Cells(2, i).Value = Cells(1, i).Value * 2
Next i
End Sub
VB解説
Cells(1, i)→ 1行目のi列目Cells(2, i)→ 2行目のi列目- ループで最終列まで繰り返し処理
例2:1行目の範囲をまとめて色付け
Sub 最終列まで色付け()
Dim lastCol As Long
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
' A1〜最終列までを黄色に
Range(Cells(1, 1), Cells(1, lastCol)).Interior.Color = vbYellow
End Sub
VB解説
Range(Cells(1,1), Cells(1,lastCol))→ A1から最終列までの範囲.Interior.Color→ 背景色を変更
例3:1行目の平均より大きいセルだけ緑に
Sub 最終列まで平均判定()
Dim lastCol As Long
Dim rng As Range
Dim avg As Double
Dim c As Range
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
' 1行目の範囲を指定
Set rng = Range(Cells(1, 1), Cells(1, lastCol))
' 平均値を計算
avg = WorksheetFunction.Average(rng)
' 各セルをチェック
For Each c In rng
If IsNumeric(c.Value) And c.Value > avg Then
c.Interior.Color = RGB(200, 255, 200) ' 薄い緑
Else
c.Interior.ColorIndex = xlNone
End If
Next c
End Sub
VBまとめ
- 最終列を調べる:
Cells(1, Columns.Count).End(xlToLeft).Column - Range と Cells を組み合わせる:
Range(Cells(1,1), Cells(1,lastCol)) - 応用: コピー、計算、色付けなどを「横方向に自動処理」できる
