本文提供完整 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 |
.Columns(colIdx).Select,若僅設定屬性,建議改用直接物件參考:.Columns(colIdx).Cells.VerticalAlignment = wdCellAlignVerticalCenterFor Each cell In .Columns(colIdx).Cells: cell.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter: NextApplication.ScreenUpdating = False 已包含,大量表格時效果顯著。On Error Resume Next 讓單一表格錯誤不中斷整體流程,正式專案建議改用 On Error GoTo ErrHandler 記錄錯誤細節。tbl.AutoFitBehavior wdAutoFitWindow 或 wdAutoFitContent。FileDialog 選擇多個文件,外層再加一層 For Each doc In Documents 迴圈。掌握 For Each tbl In Tables 迴圈模式,即可輕鬆實現任何表格批次格式化需求。