介绍使用vba语句操作word中的表格。 本文讲解word中使用vba设置表格的边框和底纹

一、表格的边框

1、边框设置的方法、属性

(1)Borders.Item 方法

1.jpg 2.jpg

(2)Border.LineStyle 属性

3.jpg

(3)Border.LineWidth 属性

4.jpg

(4)Border.ColorIndex 属性

5.jpg

2、代码示例

Sub 设置表格的边框()
  Dim t As Word.Table
  '针对文档中的所有表格
  For Each t In ActiveDocument.Tables
    '设置表格上边框
    With t.Borders(wdBorderTop)
      .LineStyle = wdLineStyleDouble '线条为双线条
      .LineWidth = wdLineWidth075pt '宽度为0.75磅
      .ColorIndex = wdDarkRed '颜色为红色
    End With
    '设置其他边框同理
  Next t
End Sub

二、表格的底纹

.Shading 对象 包含某一对象的底纹属性。 Shading.Texture 属性 返回或设置指定对象的底纹纹理。 Shading.BackgroundPatternColorIndex 属性 返回或设置应用于 Shading 对象的背景色。 Shading.ForegroundPatternColorIndex 属性 返回或设置 Shading 对象的前景色。该颜色是应用于底纹图案的点和线的颜色。

Sub 设置表格的底纹()
  Dim t As Word.Table
  '针对文档中的所有表格
  For Each t In ActiveDocument.Tables
'    设置表格第一行的底纹
    With t.Rows(1).Shading
'      .Texture = wdTextureNone '无底纹
      .Texture = wdTexture17Pt5Percent
      .BackgroundPatternColorIndex = wdAuto
      .ForegroundPatternColorIndex = wdAuto
    End With
    
    '设置表格最后一行的底纹
    With t.Rows.Last.Shading
      .Texture = wdTexture17Pt5Percent
      .BackgroundPatternColorIndex = wdAuto
      .ForegroundPatternColorIndex = wdAuto
    End With
  Next t
End Sub