如何在word文档中编写一个循环来格式化表格?

时间:2016-03-02 16:31:44

标签: vba word-vba

我一直在尝试找到一个代码,以特定方式格式化word文档的第一个表格,然后循环遍历其余表格,以另一种方式格式化它们。我找到了一个能够正确遍历所有表格的代码,但是还没有找到一种方法来排除第一个表格以便以不同方式对其进行格式化。这是适用于所有表的代码

Sub Change_All_Tables_Formating()
Dim oTbl As Word.Table
Dim oCell As Word.Cell
  For Each oTbl In ActiveDocument.Tables
  For Each oCell In oTbl.Range.Cells
  oCell.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
  Next oCell
  oTbl.Rows(1).Shading.BackgroundPatternColorIndex = wdGray25
  oTbl.Rows(1).Range.Bold = True
  Next oTbl
End Sub

这是我无法正确调整格式化第一个表格的代码。它需要完全从第一个表中删除阴影,并遮蔽word文档中其余表的标题。我觉得如果我能学会如何做到这一点,我将能够调整我想要的任何表格并单独格式化。表的数量因文档而异,但第一个表始终相同。我将不胜感激,任何人都可以提供帮助。

Sub Change_Tables_Formating()
 Dim oTbl As Word.Table
 Dim oCell As Word.Cell
 Set oTbl = ActiveDocument.Tables
 Set oTblcnt = wdDoc.Tables.Count
    For oTbl = 0 To 1
      For Each oCell In oTbl.Range.Cells
       oCell.Range.ParagraphFormat.Alignment = wdAlignParagraphLeft
      Next oCell
       oTbl.Range.Shading.BackgroundPatternColorIndex = wdColorWhite
      Next oTbl
    For oTbl = 2 To oTblct
      For Each oCell In oTbl.Range.Cells
      oCell.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
      Next oCell
      oTbl.Rows(1).Shading.BackgroundPatternColorIndex = wdGray25
      oTbl.Rows(1).Range.Bold = True
      Next oTbl
End Sub

1 个答案:

答案 0 :(得分:1)

以下是我的表现:

Sub Change_Tables_Formating()
    Dim oTbl As Word.Table, i As Long
    For Each oTbl In ActiveDocument.Tables
        i = i + 1
        If i = 1 Then
            FormatFirst oTbl
        Else
            FormatRest oTbl
        End If
    Next oTbl
End Sub

Sub FormatFirst(tbl As Table)
    Dim oCell
    For Each oCell In tbl.Range.Cells
        oCell.Range.ParagraphFormat.Alignment = wdAlignParagraphLeft
    Next oCell
    tbl.Range.Shading.BackgroundPatternColorIndex = wdColorWhite

End Sub

Sub FormatRest(tbl As Table)
    Dim oCell
    For Each oCell In tbl.Range.Cells
        oCell.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
    Next oCell
    tbl.Rows(1).Shading.BackgroundPatternColorIndex = wdGray25
    tbl.Rows(1).Range.Bold = True
End Sub