萬盛學電腦網

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

Word VBA:迴圈處理表格集合並設定邊框屬性完整範例

本文提供完整 VBA 代碼,示範如何迴圈遍歷 ActiveDocument.Tables 集合,對每個表格套用統一的邊框、底紋、對齊等格式。代碼結構清晰,適合直接套用或客製化修改。

完整巨集代碼

Sub FormatTablesLoop()
    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" ' 視版本調整名稱
            
            ' 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
                    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

核心物件與屬性對照表

物件/屬性用途常用常數
Table.Style套用內建/自訂表格樣式"表格樣式 4", "Table Grid"
Borders.InsideLineStyle內部網格線型wdLineStyleSingle, wdLineStyleDouble, wdLineStyleNone
Rows(1).Borders(wdBorderBottom)指定列特定邊框wdBorderTop, Bottom, Left, Right, Horizontal, Vertical
Shading.BackgroundPatternColor儲存格底紋顏色wdColorGray125, wdColorGray25, wdColorAutomatic, RGB值
Cells.VerticalAlignment儲存格垂直對齊wdCellAlignVerticalTop, Center, Bottom
ParagraphFormat.Alignment段落水平對齊wdAlignParagraphLeft, Center, Right, Justify

效能優化建議

  • 避免 Select:範例中為相容性使用 .Columns(colIdx).Select,若僅設定屬性,建議改用直接物件參考:
    .Columns(colIdx).Cells.VerticalAlignment = wdCellAlignVerticalCenter
    For Each cell In .Columns(colIdx).Cells: cell.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter: Next
  • 關閉螢幕更新:Application.ScreenUpdating = False 已包含,大量表格時效果顯著。
  • 錯誤處理:On Error Resume Next 讓單一表格錯誤不中斷整體流程,正式專案建議改用 On Error GoTo ErrHandler 記錄錯誤細節。

客製化擴充方向

  1. 條件式格式:依表格標題關鍵字、列數、欄數決定套用不同樣式。
  2. 欄寬自動調整:tbl.AutoFitBehavior wdAutoFitWindow 或 wdAutoFitContent。
  3. 跨文件批次:搭配 FileDialog 選擇多個文件,外層再加一層 For Each doc In Documents 迴圈。

掌握 For Each tbl In Tables 迴圈模式,即可輕鬆實現任何表格批次格式化需求。

copyright © 萬盛學電腦網 all rights reserved