1
votes

I have a document that contains the following text format that occurs throughout:

5:43-64

I want to search and replace so that the text reads like so:

5:43-64 indicates:

Fortunately, the - only appears in this type of text. The numbers change in each instance. So I don´t think I have to worry about some complicated search pattern. I can just search for the - character.

I want to then take whatever is after the the - and then save it as a variable then insert the text indicates afterward. I need this to loop through the whole document making these changes at any occurrence of the -.

Here is the code that I have up to this point that kind of half works:

Sub placeWordAfterDash()

Selection.Find.ClearFormatting
With Selection.Find
   .Text = "-"
   .Forward = True
   .Wrap = wdFindContinue
   .Format = False
   .MatchCase = False
   .MatchWholeWord = False
   .MatchWildcards = False
   .MatchSoundsLike = False
   .MatchAllWordForms = False
End With

If Selection.Find.Execute Then
    Dim selectedString As String
    Selection.Select
    selectedString = Selection.Next(Unit:=wdWord, Count:=1).Text
    Selection.Text = "-" & selectedString & " indicates: "
End If

End Sub

This code only makes the change in one instance and also leaves me with:

5:43-64 indicates: 64

Which isn´t quite what I want.

1

1 Answers

2
votes

You don't need to use vba to do this find-replace, you can do it with a simple wildcard find-replace.

press CTRL+H, find (-<*>), Replace with \1 indicates: (make sure to check "Use Wildcards")


If you do want to use vba:

Selection.Find.ClearFormatting
With Selection.Find
    .Text = "(-<*>)"
    .Replacement.Text = "\1 indicates:"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchAllWordForms = False
    .MatchSoundsLike = False
    .MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceAll