如何用vba为word文档中的所有表格自动插入题注和交叉引用?

在长篇的word文档排版中,往往需要在文档中表格的上方插入题注,同时在题注上方插入一个“XXX如YYY所示”的交叉引用。

可以使用如下的vba代码实现:

Sub QQ1722187970()
    Word.Application.ScreenUpdating = False
    Dim oRng As Range
    Dim oDoc As Document
    Dim oCL As CaptionLabel
    Dim oT As Table
    Set oDoc = Word.ActiveDocument
    With oDoc
        Set oCL = Word.CaptionLabels.Add("表")
        '设置新增的题注样式
        With oCL
            .ChapterStyleLevel = 1
            .IncludeChapterNumber = True
            .NumberStyle = wdCaptionNumberStyleArabic
        End With
        i = 1
        For Each oT In .Tables
            Set oRng = .Range(oT.Range.Start - 2, oT.Range.Start - 1)
                With oRng
        '            将oRng对象按照整个段落选中 , oRng对象自动变为整个段落的Range对象
                    oRng.Expand wdParagraph
                    '如果有自动编号,删除
                    oRng.ListFormat.RemoveNumbers
'                    读取标题的文本内容
                    sText = VBA.Replace(oRng.Text, Chr(13), "")
                    .Delete
                    '插入题注
                    .InsertCaption "表", sText
                    '插入XX如YY所示的交叉引用
                    .InsertBefore "所示:" & Chr(13)
                    '重新定义区域
                    .SetRange .Start, .Start
                    .InsertCrossReference "表", wdOnlyLabelAndNumber, i
                    oRng.Expand wdParagraph
                    .SetRange .Start, .Start
                    .InsertBefore sText & "如"
                End With
                i = i + 1
        Next
    End With
    Word.Application.ScreenUpdating = True
End Sub

 

       

发表评论