[英]Word VBA: Find and replace with ref code
我正在尝试使用域代码http://office.microsoft.com/zh-CN/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
我认为您需要在代码中使用其他类型的逻辑。 主要区别在于您需要先找到您的文本并将其选中。 下一步,您需要在选择范围内添加一个字段。 以下子例程可以帮助您改进所有这些事情。 希望这就是您想要的。 (请参阅代码内的一些注释)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.