luan_coder
luan_coder

Reputation: 1

Set specific condition to replace text in Word VBA

I'm trying to create a macro that replaces a piece of text with specific conditions.

For example:

if it's shown in the document "Summary nº 123" then keep the text the way it is,

but if it is shown "Summary 321" without the '' in the text, I want the macro to add the 'nº' between Summary and 321 (Summary nº 321) while keeping all the "Summary" followed by nº unchanged and not duplicating them (Summary nº nº 123).

I already tried to use wildcards but to no avail. Maybe I didn't use the right combination of wildcards, but I have no idea on how to solve the problem.

Upvotes: 0

Views: 128

Answers (2)

taller
taller

Reputation: 18762

  • Assuming the text string pattern is Summary+[a Space]+Digits

  • Find and Replace with wildcards

enter image description here

  • VBA code
Sub InsertNo()
    With Selection.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = "(Summary) ([0-9]{1,})"
        .Replacement.Text = "\1 n" & ChrW(186) & " \2"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchByte = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = True
        .Execute Replace:=wdReplaceAll
    End With
End Sub

enter image description here

Upvotes: 0

Black cat
Black cat

Reputation: 6097

Try this: (supposed that there is only one space between "Summary and the number or № sign.

Sub numer()
Set rng = ActiveDocument.Content
With rng.Find
  .Text = "Summary"
  Do
    .Execute
     If .Found Then
       rng.Select
       Selection.Move wdCharacter, 2
       If AscW(Selection) = &H2116 Then
       Else
         Selection.InsertAfter ChrW(&H2116) & " "
       End If
     End If
  Loop While .Found
End With
End Sub

Upvotes: 0

Related Questions