介绍使用vba语句操作word中的表格。 本文讲解word中使用vba来操作表格的行 主要为:使用vba设置word中的表格行,增加行、删除行、设置行高、设置跨页断行、设置重复标题行、设置行的水平和垂直对齐方式。
一、插入行、删除行
Sub 表格的行()
Dim t As Table
Set t = ActiveDocument.Tables(3)
' '行数
' MsgBox t.Rows.Count
' '插入1行 在第2行之前
' t.Rows.Add t.Rows(2)
' '删除 第2行
' t.Rows(2).Delete
'在第1行的上方插入2行
' 在当前选定内容上方插入行
' t.Rows.First.Select
' Selection.InsertRowsAbove 2
' 在最后一行的下方插入1行
' 在当前选定内容的下方插入行
' t.Rows.Last.Select
' Selection.InsertRowsBelow 1
End Sub
二、设置行高
Sub 表格的行()
Dim t As Table
Set t = ActiveDocument.Tables(3)
'设置行高 注意固定值和最小值的区别
' t.Rows.HeightRule = wdRowHeightAtLeast '行高值为最小值
'' t.Rows.HeightRule = wdRowHeightExactly '行高为固定值
' t.Rows.Height = CentimetersToPoints(0.75) '行高
' '设置第1行的行高
' t.Rows.First.HeightRule = wdRowHeightExactly '行高值为固定值
' t.Rows.First.Height = CentimetersToPoints(0.75) '行高
End Sub
三、跨页断行
Sub 表格的行()
Dim t As Table
Set t = ActiveDocument.Tables(3)
'允许跨页断行
'跨页断行就是允许一个表格中的一行在两个页面显示
' t.Rows.AllowBreakAcrossPages = True
End Sub
四、重复标题行
Sub 表格的行()
Dim t As Table
Set t = ActiveDocument.Tables(3)
'重复标题行
'当标题行为1行的时候
't.Rows(1).HeadingFormat = True
't.Rows.First.HeadingFormat = False
'当标题行为多行的时候
't.Rows(1).Select
'Selection.MoveDown wdLine, 1, wdExtend
'Selection.Rows.HeadingFormat = True
'标题行为前多行的时候,如此设置和上面等效
't.Rows(2).HeadingFormat = True
End Sub
五、指定行的对齐方式
Sub 表格的行()
Dim t As Table
Set t = ActiveDocument.Tables(3)
'MsgBox t.Rows(1).Cells.Count
't.Rows(1).Cells(1).Range.Text = "项目"
'Rows.Alignment 属性
'指定行的对齐方式 水平对齐 和 垂直对齐
't.Rows(1).Range.ParagraphFormat.Alignment = wdAlignRowLeft
't.Rows(1).Range.Cells.VerticalAlignment = wdCellAlignVerticalTop
End Sub