セルの結合
「範囲を結合」「横方向だけ結合」「結合解除」「結合セルの扱い」まで、初心者でも確実に使えるテンプレートをまとめます。基本は Range(…).Merge、解除は .UnMerge、状態確認は .MergeCells、結合範囲は .MergeArea です。
基本:結合と解除の最短コード
Sub MergeBasic()
'A1:B1を結合
Range("A1:B1").Merge
End Sub
Sub UnmergeBasic()
'A1:B1の結合を解除
Range("A1:B1").UnMerge
End Sub
VB- ポイント: 結合すると左上セルの値が残り、他のセルの値は消えます。複数セルに異なる値があるときは警告が出るため、必要なら DisplayAlerts を一時オフにします。
Sub MergeWithAlertsOff()
Application.DisplayAlerts = False
Range("A1:B1").Merge
Application.DisplayAlerts = True
End Sub
VB横方向だけ結合(Across)と安全な結合
Sub MergeAcrossRows()
'B2:D3の各行で横方向だけ結合(B2:D2 と B3:D3 をそれぞれ結合)
Range("B2:D3").Merge Across:=True
End Sub
Sub MergeRangeSafely()
'複数ブロックを順次結合(存在チェック+警告抑止)
Dim areas As Variant, i As Long
areas = Array("B2:D2", "B3:D3", "F5:H5")
Application.DisplayAlerts = False
For i = LBound(areas) To UBound(areas)
Range(CStr(areas(i))).Merge
Next
Application.DisplayAlerts = True
End Sub
VB- ポイント: Across:=True は「行単位で横結合」。省略または False は範囲全体を一つに結合します。
結合状態の確認と結合範囲の取得
Sub CheckMergeState()
If Range("B2").MergeCells Then
MsgBox "B2は結合セルを含みます"
Else
MsgBox "B2は未結合です"
End If
End Sub
Sub GetMergeArea()
'B2が結合セルなら、その結合範囲全体を選択
If Range("B2").MergeCells Then
Range("B2").MergeArea.Select
End If
End Sub
VB- ポイント: MergeCells で結合有無を判定、MergeArea で「結合されている塊」を丸ごと取得できます。
実務テンプレート:表の見出し結合+中央揃え
Sub MergeHeaderAndCenter()
With Range("B2:D2")
.Merge
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.Font.Bold = True
End With
End Sub
VB- ポイント: 見出し結合は「中央揃え」「太字」をセットで。結合は操作や並べ替えに弱いので、必要最小限にとどめます。
例題で練習
例題1:週報の見出しを行ごとに横結合
Sub Example_WeeklyHeaders()
Dim r As Long
For r = 2 To 10 Step 2
Range("B" & r & ":E" & r).Merge Across:=True
Range("B" & r & ":E" & r).HorizontalAlignment = xlCenter
Next
End Sub
VB例題2:表中の結合セルを一覧でハイライト
Sub Example_HighlightMergeAreas()
Dim cell As Range, area As Range
For Each cell In Range("A1").CurrentRegion
If cell.MergeCells Then
Set area = cell.MergeArea
area.Interior.Color = RGB(255, 242, 204) '薄い黄色
End If
Next
End Sub
VB例題3:結合解除→値の整形→必要な箇所だけ再結合
Sub Example_UnmergeThenFormat()
Dim rg As Range
Set rg = Range("B2:E20")
'一旦すべて解除
rg.UnMerge
'体裁を整える(例:見出し中央)
With Range("B2:E2")
.HorizontalAlignment = xlCenter
.Font.Bold = True
End With
'必要箇所のみ再結合
Range("B2:E2").Merge
End Sub
VB実務の落とし穴と対策
- 値の消失・警告ダイアログ: 結合時は左上以外の値が消える。必要なら事前に値を退避、もしくは DisplayAlerts をオフにして手順を管理。
- 並べ替え・フィルタとの相性: 結合セルは操作に制約が多い。見出しなど最小限に限定し、データ部の結合は避ける。
- 結合範囲の誤指定: 斜めに離れたセルは結合できない。範囲は必ず連続セルで指定。
- 結合状態の見落とし: 処理前に .MergeCells で判定し、結合済みなら .MergeArea を使って塊ごとに扱う。
