如何用vba在word文档中插入交叉引用?

在word中用vba插入交叉引用,可以使用Range对象或Selection对象的IInsertCrossReference方法。

它的语法如下:

Sub InsertCrossReference(ReferenceType, ReferenceKind As WdReferenceKind, ReferenceItem, [InsertAsHyperlink], [IncludePosition], [SeparateNumbers], [SeparatorString])

其中各个参数的说明如下:

Name Required/Optional Data type Description
ReferenceType Required Variant The type of item for which a cross-reference is to be inserted. Can be anyWdReferenceType or WdCaptionLabelID constant or a user defined caption label.
ReferenceKind Required WdReferenceKind The information to be included in the cross-reference.
ReferenceItem Required Variant If ReferenceType is wdRefTypeBookmark , this argument specifies a bookmark name. For all other ReferenceType values, this argument specifies the item number or name in the Reference type box in the Cross-reference dialog box. Use the GetCrossReferenceItemsmethod to return a list of item names that can be used with this argument.
InsertAsHyperlink Optional Variant True to insert the cross-reference as a hyperlink.
IncludePosition Optional Variant True to insert “above” or “below,” depending on the location of the reference item in relation to the cross-reference.
SeparateNumbers Optional Variant True to use a separator to separate the numbers from the associated text. (Use only if the ReferenceType parameter is set to wdRefTypeNumberedItem and the ReferenceKind parameter is set to wdNumberFullContext.)
SeparatorString Optional Variant Specifies the string to use as a separator if the SeparateNumbers parameter is set to True.

以下vba代码举例演示在word文档的开头插入一个交叉引用,该交叉引用引用的是第一个自定义题注标签”表”。

Sub QQ1722187970()
   Dim oRng As Range
   Dim oDoc As Document
   Set oDoc = Word.ActiveDocument
   Set oRng = oDoc.Range(0, 0)
   With oRng
        .InsertCrossReference "表", wdOnlyLabelAndNumber, 1
   End With
End Sub

如果想要获取某个类型的所有可用的交叉引用,可以使用Document对象的GetCrossReferenceItems方法。

如下所示:

Sub QQ1722187970()
   Dim oRng As Range
   Dim oDoc As Document
   Set oDoc = Word.ActiveDocument
   Set oRng = oDoc.Range(0, 0)
   With oRng
        '获取所有可用的交叉引用项
        arrItems = oDoc.GetCrossReferenceItems("表")
        '插入最后一个交叉引用项
        .InsertCrossReference "表", wdOnlyLabelAndNumber, UBound(arrItems)
   End With
End Sub

 

       

发表评论