0

我正在尝试使用域代码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
4

1 回答 1

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
于 2013-08-29T13:54:51.667 回答