Word VBA:查找并替换为ref代码

时间:2013-08-28 20:04:59

标签: vba ms-word word-vba

我正在尝试使用字段代码http://office.microsoft.com/en-us/word-help/field-codes-ref-field-HP005186139.aspx

查找并替换其中的括号和文本
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

1 个答案:

答案 0 :(得分: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
相关问题