使用VBA获取单词中的所有交叉引用

时间:2014-07-25 08:39:58

标签: vba ms-word word-vba

我有一个很大的word文档(> 400页),其中包含很多标题的交叉引用。到目前为止,我总是提到标题的标题,但现在我想改变它并参考标题所在的页面。

我没有通过GUI找到解决方案(当然除了手动处理),所以我正在研究编写一些VBA。不幸的是,我只找到了一种方法来列出所有可以交叉引用的目标(通过GetCrossReferenceItems),但我需要一种方法来访问实际的交叉引用字段。

你可以帮帮我吗?交叉引用字段是否与超链接相同?

1 个答案:

答案 0 :(得分:6)

交叉引用是Word文档中的字段,可以通过Fields集合(ActiveDocument.Fields)进行访问。您可以像任何其他集合一样遍历它们并检查它们的类型,看它是否是您想要处理的类型。看起来对文本的交叉引用是类型3(wdFieldRef),并且对页码的交叉引用是类型37(wdFieldPageRef)。改变领域可能有点棘手;以下内容应该让你开始:

Sub ChangeFields()
    Dim objDoc As Document
    Dim objFld As Field
    Dim sFldStr As String
    Dim i As Long, lFldStart As Long

    Set objDoc = ActiveDocument
    ' Loop through fields in the ActiveDocument
    For Each objFld In objDoc.Fields
        ' If the field is a cross-ref, do something to it.
        If objFld.Type = wdFieldRef Then
            'Make sure the code of the field is visible. You could also just toggle this manually before running the macro.
            objFld.ShowCodes = True
            'I hate using Selection here, but it's probably the most straightforward way to do this. Select the field, find its start, and then move the cursor over so that it sits right before the 'R' in REF.
            objFld.Select
            Selection.Collapse wdCollapseStart
            Selection.MoveStartUntil "R"
            'Type 'PAGE' to turn 'REF' into 'PAGEREF'. This turns a text reference into a page number reference.
            Selection.TypeText "PAGE"
            'Update the field so the change is reflected in the document.
            objFld.Update
            objFld.ShowCodes = True
        End If
    Next objFld   
End Sub