2013-08-28 33 views
0

我試圖找到並與域代碼http://office.microsoft.com/en-us/word-help/field-codes-ref-field-HP005186139.aspx字VBA:查找和裁判的代碼替換

Sub replacereftag() 
    ReplacementText "<test>", "REF Test.Test1 " 
End Sub 

Private Sub ReplacementText(findtext As String, replacetext As String) 
    Selection.Find.ClearFormatting 
    Selection.Find.Replacement.ClearFormatting 
    With Selection.Find 
     .Text = findtext 
     .myrange.Field = replacetext 
     .Wrap = wdFindContinue 
     .MatchWildcards = True 
    End With 
    Selection.Find.Execute Replace:=wdReplaceAll 
End Sub 
+0

問題是什麼? – Rick

+0

我試圖替換字段代碼ref部分,但在這一點上我還沒有成功。它取代了文本,但不作爲參考文件。我只是想弄清楚參考代碼 – Jon

+0

它仍然有點不清楚 - 你是否試圖用'Field object'替換文檔中的某些文本? –

回答

0

在我看來,你需要使用不同類型的邏輯在更換它的支架和文字的碼。主要區別在於您需要先找到您的文本並選擇它。作爲下一步,您需要在選擇範圍內添加一個字段。下面的子程序改進了你所做的所有這些事情。希望這是你正在尋找的。 (見代碼裏面的一些評論)

Sub replacereftag() 
    ReplacementText "<test>", "REF Test.Test1 " 
    'if you keep .MatchWildcards = True below then call next sub in this way: 
    'ReplacementText "\<test\>", "REF Test.Test1 " 
End Sub 

Private Sub ReplacementText(findtext As String, replacetext As String) 
    Selection.Find.ClearFormatting 
    Selection.Find.Replacement.ClearFormatting 
    With Selection.Find 
     .Text = findtext 
     'I removed something here 
     .Wrap = wdFindContinue 
     .MatchWildcards = False '!!!- both <> are special characters!! 
    End With 

    'looping to search for all occurrences 
    Do While Selection.Find.Execute 
     'add a field here 
     Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _ 
      "REF Test.Test1", PreserveFormatting:=False 
    Loop 
End Sub 

編輯

Sub replacereftag() 
    ReplacementText "<test>", "REF Test.Test" 

    Dim i 
    for i=1 to 10   'change to last number 
     ReplacementText "<test" & i & ">", "REF Test.Test" & i 
    next i 
End Sub 
+0

謝謝KazJaw你會如何改善搜索位置我有多個引用需要被替換,例如。 成爲ref test.test並且變爲ref test.test1等 – Jon

+0

@Jon,請參閱答案的版本... –