介绍使用vba语句操作word中的表格。 本文讲解word中使用vba来操作表格的列 主要为:使用vba设置word中的表格列,增、删列、设置列高、设置列的水平和垂直对齐方式。
一、插入列、删除列
Sub 表格的列()
Dim t As Table
Set t = ActiveDocument.Tables(1)
' '计算列数
' MsgBox t.Columns.Count
' '增加1列,在第2列之前
' t.Columns.Add t.Columns(2)
' '删除指定的列
' t.Columns(2).Delete
'插入列
'在左侧插入1列
t.Columns(2).Select
Selection.InsertColumns
'在右侧插入1列
t.Columns(3).Select
Selection.InsertColumnsRight
End Sub
二、设置列宽
Sub 表格的列()
Dim t As Table
Set t = ActiveDocument.Tables(1)
' .PreferredWidthType 属性
' 返回或设置用于指定单元格/列/表格的首选度量单位
' wdPreferredWidthAuto '自动宽度
' wdPreferredWidthPercent '百分比
' wdPreferredWidthPoints '磅
'.PreferredWidth
'返回或设置指定列的首选宽度(以磅为单位或表示为窗口宽度的百分比)
'表达式.CentimetersToPoints (Centimeters)
'将度量单位由厘米转换为磅数(1 厘米=28.35 磅)
'' 首先 要设置表格的尺寸
' t.PreferredWidthType = wdPreferredWidthAuto '即 不指定表格宽度
' t.PreferredWidth = 0
'' 其次 再设置列宽
' t.Columns.PreferredWidthType = wdPreferredWidthPoints '磅
' t.Columns.PreferredWidth = CentimetersToPoints(4) '4厘米
''设置指定列的宽度
' t.Columns(3).PreferredWidthType = wdPreferredWidthPoints '磅
' t.Columns(3).PreferredWidth = CentimetersToPoints(8) '8厘米
End Sub
三、指定列的对齐方式
Sub 表格的列()
Dim t As Table
Set t = ActiveDocument.Tables(1)
'设置指定列的对齐方式
With t.Columns(1)
.Cells.VerticalAlignment = wdCellAlignVerticalCenter ' 垂直居中
'水平靠左
Dim c As Integer
For c = 1 To .Cells.Count
.Cells(c).Range.ParagraphFormat.Alignment = wdAlignParagraphLeft
Next c
End With
End Sub