萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 辦公室軟體 >  >> Word 教學 >> Word 使用技巧

Word VBA 批次設定表格樣式:邊框、底紋、對齊一次搞定

需對文件中所有表格套用統一格式(邊框、標題列底紋、欄位置中)時,逐一手動設定極耗時。本文提供完整 VBA 代碼,可一次對 ActiveDocument.Tables 集合內所有表格套用預設樣式。

完整 VBA 代碼

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

代碼邏輯詳細說明

1. 樣式套用 .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

2. 邊框設定 .Borders 集合

  • InsideLineStyle:控制儲存格內部網格線。
  • OutsideLineStyle:控制表格外框(本範例未設定,保留樣式預設)。
  • 特定邊框用 .Borders(wdBorderBottom) 等索引存取。

3. 底紋判斷邏輯

Len(.Cell(2, 1).Range.Text) <= 2 用於偵測第二列第一欄是否為空。Word 儲存格內容最少含 vbCr (Chr(13)) 與 vbCr & Chr(7) 兩字元,故長度 ≤ 2 視為空白。

4. 選取式對齊設定

代碼使用 .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 判斷。
copyright © 萬盛學電腦網 all rights reserved