水曜日, 7月 16, 2025

Excel VBA 47 
Excelで選択したエリアを一列おきに選択

Excelで選択したエリアを一行おきに選択し、色を設定します。
デフォルト環境で設定するのが面倒くさいので作成した一行版の一列版です。

Sub SelectAlternateColumnsWithinSelection()
Dim rng As Range
Dim colRange As Range
Dim newSelection As Range
Dim colIndex As Integer
' 選択範囲を取得
On Error Resume Next
Set rng = Selection
On Error GoTo 0
' 範囲が選択されていない場合、エラーを表示
If rng Is Nothing Then
MsgBox "セル範囲を選択してください。", _
vbExclamation, "エラー"
Exit Sub
End If

' 選択範囲の1列おきの列を取得
For colIndex = 1 To rng.Columns.Count Step 2
Set colRange = rng.Columns(colIndex)
If newSelection Is Nothing Then
Set newSelection = colRange
Else
Set newSelection = Union(newSelection, colRange)
End If
Next colIndex

' 選択を適用
If Not newSelection Is Nothing Then
newSelection.Select
End If

MsgBox "選択範囲内の1列おきの列を選択しました!", _
vbInformation, "完了"
End Sub

エリアを選択し・・・

実行すると1列おきに選択した状態になるので・・・

カラーパレットで任意の色を設定。
シンプルな動きの方が応用が利きますね。