2013-12-16 63 views
0

我有一個單詞doc中的某些文本是書籤。我想用Word VBA解析文檔中的相同單詞並插入交叉引用。由於某些原因,當我插入交叉引用時,代碼不會移動到下一個單詞。解析Word文檔插入交叉引用

Sub ReplaceTextwithCrossRef() 

Dim BMtext As String 
Dim BMname As String 
Dim Sel As Selection 
Set Sel = Application.Selection 

BMname = Sel.Bookmarks(1).Name 
BMtext = Sel.Text 
MsgBox BMname 
MsgBox BMtext 

For Each oWd In ActiveDocument.Words 

oWd.Select 

If oWd.Text = BMtext Then 

If Selection.Bookmarks.Exists(BMname) Then 

Else 

Selection.InsertCrossReference ReferenceType:=wdRefTypeBookmark, _ 
     ReferenceKind:=wdContentText, ReferenceItem:=BMname 

Selection.MoveDown Unit:=wdLine, Count:=1 

End If 

Else 

End If 

Next oWd 

End Sub 

用戶選擇書籤單詞,代碼移動到單詞的下一個實例,並交叉引用它。即

BOOKMARKEDITEM

WORDS1

WORDS2

BOOKMARKEDITEM

WORDS3

將插入上BOOKMARKEDITEM的第二個實例的交叉引用,但它不會移動到WORDS3。即使我告訴它隨着下一行代碼向下移動,它仍然卡住並繼續回到交叉引用。任何幫助,將不勝感激。

回答

1

我解決了我自己的問題。使用'Do','With'和'If-Else'陳述,而不是遍歷每個單詞。由於某種原因,我認爲交叉參考插入螺絲會固定在'For'環上。這裏是解決方案:

Sub ReplaceTextwithCrossRef() 

    Dim BMtext As String 
    Dim BMname As String 
    Dim Counter As Long 
    Dim Counter2 As Long 

    Dim Sel As Selection 
    Set Sel = Application.Selection 

    'Select the bookmark 
    BMname = Sel.Bookmarks(1).Name 
    BMtext = Sel.Text 
    MsgBox "This is the bookmark: " & BMname 
    ' MsgBox BMtext 

    'Select all of the document and search 
    ActiveDocument.Range.Select 
    Do 
     With Selection.Find 
      .ClearFormatting 
      .Text = BMtext 
      .Replacement.Text = "" 
      .Format = False 
      .MatchWildcards = False 
      .Wrap = wdFindStop 
      .Execute 
     End With 

     If Selection.Find.Found Then 
     'Overall counter 
      Counter = Counter + 1 
       'Check if the select is bookmarked 
       If Selection.Bookmarks.Exists(BMname) Then 
        'Do nothing and move on 
       Else 
        'Insert the cross referebce 
        Selection.InsertCrossReference ReferenceType:=wdRefTypeBookmark, _ 
        ReferenceKind:=wdContentText, ReferenceItem:=BMname 
        Counter2 = Counter2 + 1 
       End If 
     End If 
    Loop Until Not Selection.Find.Found 

    'Tell how many we found 
    MsgBox "We found " & Counter & " instances of " & BMtext & " and " & Counter2 & " cross references were made." 

End Sub 

編輯:添加代碼添加CHARFORMAT

如果你想原始格式保持插入交叉引用之前,使用「計數器2」和端之間下面的代碼If語句來編輯域代碼。我在網上搜索了很長時間,發現了一些可以工作的東西,這就是我想出來的東西:

Dim oField As Field 
    Dim sCode As String 
    'Move left and select the reference 
        Selection.MoveLeft Unit:=wdWord, Count:=1 
        Selection.Expand Unit:=wdWord 
    'Check reference and add Charformat 
        For Each oField In Selection.Fields 
         If oField.Type = wdFieldRef Then 
          sCode = oField.Code.Text 
          If InStr(sCode, "Charformat") = 0 Then oField.Code.Text = sCode & "\*Charformat" 
         End If 
        Next 
    'Move the cursor past the cross reference 
        Selection.Fields.Update 
        Selection.MoveRight Unit:=wdWord, Count:=1