2014-07-25 26 views
2

我有一個很大的單詞文檔(> 400頁),其中包含大量對標題的交叉引用。到目前爲止,我一直提到標題的標題,但現在我想改變它並引用標題所在的頁面。使用VBA獲取所有的單詞交叉引用

我沒有通過GUI找到解決方案(當然除了手動處理),所以我正在考慮編寫一些VBA。不幸的是,我只找到一種方法來列出所有可交叉引用的目標(通過GetCrossReferenceItems),但我需要一種方法來訪問實際的交叉引用字段。

你能幫我嗎?交叉引用字段與超鏈接相同嗎?

回答

5

交叉引用是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 
+0

太棒了,這工作得很好。我只是簡單地擴展它,使它遍歷所有StoryRanges。非常感謝。 – kaufmanu