需對文件中所有表格套用統一格式(邊框、標題列底紋、欄位置中)時,逐一手動設定極耗時。本文提供完整 VBA 代碼,可一次對 ActiveDocument.Tables 集合內所有表格套用預設樣式。
Sub FormatAllTables()
Dim tbl As Table
Dim colIdx As Integer
On Error Resume Next ' 忽略個別表格錯誤,繼續處理下一個
Application.ScreenUpdating = False
For Each tbl In ActiveDocument.Tables
With tbl
' 1. 套用內建樣式(需確認樣式名稱存在)
.Style = "表格樣式 4" ' 中文版常見名稱;英文版為 "Table Grid 4" 或 "List Table 4"
' 2. 設定內部邊框為單線
With .Borders
.InsideLineStyle = wdLineStyleSingle
.InsideLineWidth = wdLineWidth050pt
.InsideColor = wdColorAutomatic
End With
' 3. 第一列(標題列)底部雙線
With .Rows(1).Borders(wdBorderBottom)
.LineStyle = wdLineStyleDouble
.LineWidth = wdLineWidth050pt
.Color = wdColorAutomatic
End With
' 4. 第二列若非空白則套用灰色底紋
If .Rows.Count > 1 Then
If Len(.Cell(2, 1).Range.Text) <= 2 Then ' 僅含段落標記視為空白
With .Rows(2).Shading
.Texture = wdTextureNone
.ForegroundPatternColor = wdColorAutomatic
.BackgroundPatternColor = wdColorGray125 ' 灰色 12.5%
End With
End If
End If
' 5. 第 2 欄起所有欄位文字水平置中 + 垂直置中
For colIdx = 2 To .Columns.Count
.Columns(colIdx).Select
Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
Selection.Cells.VerticalAlignment = wdCellAlignVerticalCenter
Next colIdx
End With
Next tbl
Application.ScreenUpdating = True
MsgBox "所有表格格式化完成!", vbInformation
End Sub
.Style = "表格樣式 4"Word 內建表格樣式名稱會隨語系版本不同。若執行報錯,請改用英文名稱或自訂樣式名稱。可透過下列巨集列出目前文件可用樣式:
Sub ListTableStyles()
Dim s As Style
For Each s In ActiveDocument.Styles
If s.Type = wdStyleTypeTable Then Debug.Print s.NameLocal, s.Name
Next
End Sub
.Borders 集合InsideLineStyle:控制儲存格內部網格線。OutsideLineStyle:控制表格外框(本範例未設定,保留樣式預設)。.Borders(wdBorderBottom) 等索引存取。Len(.Cell(2, 1).Range.Text) <= 2 用於偵測第二列第一欄是否為空。Word 儲存格內容最少含 vbCr (Chr(13)) 與 vbCr & Chr(7) 兩字元,故長度 ≤ 2 視為空白。
代碼使用 .Columns(N).Select 搭配 Selection 物件設定對齊,雖非純物件導向寫法,但在 Word VBA 中相容性最好。若追求效能可改用:
.Columns(colIdx).Cells.VerticalAlignment = wdCellAlignVerticalCenter
For Each cell In .Columns(colIdx).Cells
cell.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
Next
If InStr(tbl.Range.Text, "關鍵字") > 0 Then 判斷。