Word VBA常用代码合集

VBA说

共 2553字,需浏览 6分钟

 · 2022-05-28

▎写在前面

都说写VBA像累积木,除了核心部分的循环逻辑思路,其余都是再堆砌代码。这篇文章就罗列一下我在写Word VBA程序中,常用的一些代码。




今天先介绍操作Word表格部分。



•新建表格


在光标位置,新建一个1行3列的表格,边框线设置为实线。

sub testSet tb = ActiveDocument.Tables.Add(Selection.Range, 1, 3)tb.Style = "网格型"end sub



•向表格里面写入值


两种方式

Sub 第一种写入方法()    Dim t As Table        Set t = ActiveDocument.Tables(1)        t.Cell(1, 1).Range = 1End Sub
Sub 第二种写入方法() Set t = ActiveDocument.Tables(1).Range For i = 1 To t.Cells.Count t.Cells(i).Range = i NextEnd Sub



•设置表格列宽


设置表格的列宽,其中需要注意单位的转换。厘米和磅。

Sub 设置word表格的宽度()     Dim tbl As Table    Set tbl = ActiveDocument.Tables(2)    tbl.Columns(1).Width = Application.CentimetersToPoints(1.42)    tbl.Columns(2).Width = Application.CentimetersToPoints(5.07)    tbl.Columns(3).Width = Application.CentimetersToPoints(2.13)    tbl.Columns(4).Width = Application.CentimetersToPoints(4.33)    tbl.PreferredWidth = Application.CentimetersToPoints(18.99)End Sub



•判断光标是否在表格中


利用的是information方法判断

Sub 判断光标是否在表格里()    If Selection.Information(wdWithInTable) = True Then        MsgBox "光标在表格里"    Else        MsgBox "光标不在表格里"    End IfEnd Sub



•表格中插入多行


Sub 表格最后插入2行()   Dim myTable As Table    Set myTable = ActiveDocument.Tables(1)    myTable.Rows.Last.Select    Selection.InsertRowsBelow 2End Sub





•向表格末尾插入内容并居中


利用move方法,移动光标,写内容


Sub 向表格末尾插入内容并居中()    Dim tbl As Word.Table    For Each tbl In Selection.Range.Tables        tbl.Range.Cells(tbl.Range.Cells.Count).Select        Selection.Move wdCharacter, 2        Selection.TypeParagraph        Selection.Move wdParagraph, -1        Selection.TypeText "表格X"        Selection.Extend        '/字体格式        With Selection.Range.Font            .Color = -16777216            .NameFarEast = "宋体"            .Size = 10 '字号 四号            .Bold = 0 '加粗为1,不加粗为0        End With        With Selection.ParagraphFormat            .LineSpacing = 20 '行间距20磅            .Alignment = wdAlignParagraphCenter '居中显示        End With    NextEnd Sub




•表格居中


内容居中,表格整体居中

Sub 向表格末尾插入内容并居中()    '将表格内容调整为上下,左右居中    For Each oTable In oDoc.Tables        oTable.AutoFitBehavior (wdAutoFitWindow)               '根据窗口调整内容        oTable.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter    '水平居中        oTable.Range.Cells.VerticalAlignment = wdCellAlignVerticalCenter    '垂直居中        oTable.Rows.Alignment = wdAlignRowCenter               '表格整体居中    NextEnd Sub




•选中第二页第一个表格


Sub test()  With Selection    .GoTo wdGoToPage, , 2    .Bookmarks("\Page").Range.Tables(2).Select  End WithEnd Sub



推荐阅读:(点击下方标题即可跳转)


浏览 91
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报