[英]Word VBA: Find and replace with ref code
I am trying to find and replace the brackets and text in it with a field code http://office.microsoft.com/en-us/word-help/field-codes-ref-field-HP005186139.aspx 我正在尝试使用域代码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
In my opinion you need to use different kind of logic in your code. 我认为您需要在代码中使用其他类型的逻辑。 The main difference is that you need to find your text first and select it.
主要区别在于您需要先找到您的文本并将其选中。 As a next step you need to add a field in the range of selection.
下一步,您需要在选择范围内添加一个字段。 The following subroutines are improved your ones doing all these things.
以下子例程可以帮助您改进所有这些事情。 Hope it's what you are looking for.
希望这就是您想要的。 (See some comments inside the code)
(请参阅代码内的一些注释)
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
Edit 编辑
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.