I have a series of report migrations I am trying to do and am looking for a method to make it a little easier. I will be copying a lot of fields from Crystal ({command.somename}) over to Word. What I would like to do is then replace Command.somename into a Mergefield somename, where the name is the dynamic variable. I am new to VBA and I have read a similar item to change a specifc word, but am not sure what to alter to have that word search be dynamic for the word after "Command." Example change command.srent to a mergefield { mergefield srent } (<<srent>>).
Any help would be appreciated. I'm starting into this so haven't honestly done a lot of research
Any help would be appreciated. I'm starting into this so haven't honestly done a lot of research.
CodePudding user response:
For example:
Sub Demo()
Application.ScreenUpdating = False
Dim StrFld As String
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "\{*\}"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = True
End With
Do While .Find.Execute
StrFld = "MERGEFIELD " & Replace(Replace(.Text, "{command.", ""), "}", "")
.Text = vbNullString
.Fields.Add Range:=.Duplicate, Type:=wdFieldEmpty, Text:=StrFld, Preserveformatting:=False
.Collapse wdCollapseEnd
Loop
End With
Application.ScreenUpdating = True
End Sub
CodePudding user response:
I was able to solve the issue with the use of .Words.Parent. The issue with the suggested code was that it was returning the search .Text not the found word within the search text. Then iterating through each instance with variable i I was able to isolate each found word within the found range and replace that word with a {mergefield }. Once done a quick F9 in Word and it updated all the new mergefields. Thanks for the help and direction @macropod is was very helpful
Sub ReplaceCommandtoMergefield()
Application.ScreenUpdating = False
Dim StrFld As String
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "Command\."
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = True
End With
Do While .Find.Execute
'MsgBox .Words.Parent
StrFld = Replace(.Words.Parent, "Command.", "")
.Words.Parent.Delete
.Fields.Add Range:=.Duplicate, Type:=wdFieldMergeField, Text:=StrFld, Preserveformatting:=True
.Text = vbNullString
.Collapse wdCollapseEnd
Loop
End With
Application.ScreenUpdating = True
End Sub
