すべてのテーブルのセル結合を解除するWordマクロを考えてみました(Word 2003と2010で動作を確認)。
ExcelのUnMergeのように結合を解除するメソッドが標準で用意されていないので、若干複雑な処理になっています。
特に横方法の結合については判別がややこしく、下記のコードではテーブルのXMLから取得しています。
※ 下記コードは入れ子になっているテーブルには未対応です。
Option Explicit
Private Sub UnMergeAllTables()
'全テーブルの結合解除
UnMergeAllTablesR
UnMergeAllTablesC
Selection.HomeKey Unit:=wdStory
End Sub
Private Sub UnMergeAllTablesR()
'全テーブルの縦方向の結合解除
Dim rowspan As Long
Dim t As Word.Table
Dim c As Word.Cell
For Each t In ActiveDocument.Tables
For Each c In t.Range.Cells
c.Select
With Selection
rowspan = (.Information(wdEndOfRangeRowNumber) - .Information(wdStartOfRangeRowNumber)) + 1
If rowspan <> 1 Then
.Cells.Split NumRows:=rowspan, NumColumns:=1, MergeBeforeSplit:=False
End If
End With
Next
Next
End Sub
Private Sub UnMergeAllTablesC()
'全テーブルの横方向の結合解除
Dim t As Word.Table
For Each t In ActiveDocument.Tables
UnMergeTableC t
Next
End Sub
Private Sub UnMergeTableC(ByRef tbl As Word.Table)
'指定したテーブルの横方向の結合解除
Dim d As Object
Dim colspan As Long
Dim i As Long, n As Long
Set d = CreateObject("MSXML2.DOMDocument")
If d.LoadXML(tbl.Range.XML) Then
With d.SelectNodes("/w:wordDocument/w:body/wx:sect/w:tbl/w:tr")
For i = 0 To .Length - 1
With .Item(i).SelectNodes("w:tc")
For n = 0 To .Length - 1
If .Item(n).SelectNodes("w:tcPr/w:gridSpan").Length > 0 Then
colspan = CLng(.Item(n).SelectNodes("w:tcPr/w:gridSpan").Item(0).Attributes(0).Text)
'Debug.Print colspan, tbl.Cell(i + 1, n + 1).Range.Text '確認用
tbl.Cell(i + 1, n + 1).Split NumRows:=1, NumColumns:=colspan
End If
Next
End With
Next
End With
End If
End Sub

















この記事へのコメントはありません。