分享

word vba 操作表格, 设置表格的单元格(拆分合并单元格)

 jeanwa 2023-02-21 发布于福建

设置单元格的边距和间距、设置合并单元格合拆分单元格。

一、单元格的边距和间距

Sub 设置单元格边距() With ActiveDocument.Tables(1) ' 返回或设置表格中所有单元格的内容的 ' 上方、下方、左方、右方 要增加的间距(以磅为单位) .TopPadding = CentimetersToPoints(0) .BottomPadding = CentimetersToPoints(0) .LeftPadding = CentimetersToPoints(0.2) .RightPadding = CentimetersToPoints(0.2) ' 返回或设置表格中单元格的间距(以磅为单位)。可读写 Single 类型。 ' 一般不做设置 不勾选 ' .Spacing = CentimetersToPoints(0.1) .Spacing = 0 ' 对指定表格 允许断页 .AllowPageBreaks = True ' 允许自动重调尺寸 .AllowAutoFit = True End With End Sub
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

二、单元的合并和拆分

1、合并单元格

Sub 合并单元格()
  '选中单元格range('a1:a2')进行合并
  Dim rng As Range
  '定义要合并的单元格区域
  Set rng = ActiveDocument.Range(ActiveDocument.Tables(1).Cell(1, 1).Range.Start, _
  ActiveDocument.Tables(1).Cell(2, 1).Range.End)
  '选中
  rng.Select
  
  '如果选择的在表格中 ,则:
  If Selection.Information(wdWithInTable) Then
  '合并
    Selection.Cells.Merge
  End If
  
  With ActiveDocument.Tables(1).Cell(1, 1)
    .Range.Text = '项目' '写入内容
    .Range.ParagraphFormat.Alignment = wdAlignParagraphCenter '水平居中
    .Range.Cells.VerticalAlignment = wdCellAlignVerticalCenter '垂直居中
  End With
End Sub
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
Sub 合并表格方法2() 'Cell.Merge 方法 '表达式.Merge (MergeTo) '将指定单元格与另一表格单元格合并,成为一个单独的表格单元格 '将表格的1行1列至2行1列合并 Dim t As Table Set t = ActiveDocument.Tables(1) With t .Cell(1, 1).Merge .Cell(2, 1) End With End Sub
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

结果展示
word vba 操作表格, 设置表格的单元格(拆分合并单元格)_合并单元格

2、拆分单元格

Sub 拆分单元格()
'  ActiveDocument.Tables(1).Cell(1, 1).Range.Select
'  Selection.Cells.Split NumRows:=2, NumColumns:=1, MergeBeforeSplit:=False

  ActiveDocument.Tables(1).Cell(1, 2).Range.Select
  Selection.Cells.Split NumRows:=1, NumColumns:=4, MergeBeforeSplit:=False
End Sub

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

结果
word vba 操作表格, 设置表格的单元格(拆分合并单元格)_合并单元格_02

三、判断是否存在合并单元格

Sub 判断是否存在合并单元格() Dim cell_count%, row_count%, column_count% With ActiveDocument.Tables(1) cell_count = .Range.Cells.Count '单元格的个数,合并的单元格计算为1个 row_count = .Rows.Count '行数 column_count = .Columns.Count '列数 '如果单元格的个数小于行数乘以列数 If cell_count < row_count * column_count Then MsgBox '存在合并单元格' Else MsgBox '不存在合并单元格' End If End With End Sub
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多