[英]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.