以下VBA代碼可使每個表格及其標題排在同一頁。我們假設表格標題位於表格的上一段。
Sub KeepRowsTogether()
Dim para As Paragraph, currCell As Cell, tabIdx As Integer
tabIdx = 0
For Each para In ActiveDocument.Paragraphs
If para.Range.Tables.Count > 0 Then
If ActiveDocument.Range(0, para.Range.End).Tables.Count <> tabIdx Then
para.Previous(1).KeepWithNext = True
With para.Range.Tables(1)
.Range.Paragraphs.KeepWithNext = True
If .Uniform = True Then ' No cell merged vertically
For Each currCell In .Rows.Last.Range.Cells ' Just set last row to false
currCell.Range.Paragraphs.Last.KeepWithNext = False
Next currCell
Else ' Else start from the last cell (bottom right)
Set currCell = .Range.Cells(.Range.Cells.Count)
Do While currCell.ColumnIndex > 1 ' Set all cell to false until the first column
currCell.Range.Paragraphs.Last.KeepWithNext = False
Set currCell = currCell.Previous
Loop
currCell.Range.Paragraphs.Last.KeepWithNext = False ' Set first column, last row to false
' ___________
' |___|___|___|
' | |___|___|
' | x |___|___|
' |___|_x_|_x_|
' <----------
End If
End With
tabIdx = tabIdx + 1
End If
End If
Next para
End Sub
參考
https://www.msofficeforums.com/word-vba/6855-keeping-table-one-page.html