Ugur
Ugur

Reputation: 312

word vba conditional find and replace

I'm trying to get MSWord's vba to replace one word: "an" with "a(n)" if the next word is "---- ". I managed to write this, but it doesn't seem to work. Any ideas why? (I also need to do the same for the word "a" with the same condition as well, but couldn't get the first one done yet, so..) By the way, I don't have a set range, I need to scan all the document..

Sub Makro1()
With Selection
  Set Rng = .Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "an"
    .Forward = True
    .Wrap = wdFindStop
    .MatchCase = False
    .MatchWholeWord = True
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    .Execute
  End With
  Do While .Find.Found
    If Selection.Next(Unit:=wdWord, Count:=1) = "---- " Then
    .Find.Replacement.Text = "a(n)"
    End If
    .Find.Execute
  Loop

End With

End Sub

Upvotes: 0

Views: 2491

Answers (2)

macropod
macropod

Reputation: 13505

You don't need a macro for this; it can all be done with a wildcard Find/Replace, where:

Find = [an]{1,2}( [_]{1,})

Replace = a(n)\1

Of course, it can also be done with a wildcard Find/Replace macro:

Sub Demo()
With ActiveDocument.Range.Find
  .ClearFormatting
  .Replacement.ClearFormatting
  .Text = "[an]{1,2}( [_]{1,})"
  .Replacement.Text = "a(n)\1"
  .Forward = True
  .Wrap = wdFindContinue
  .Format = False
  .MatchWildcards = True
  .Execute Replace:=wdReplaceAll
End With
End Sub

Upvotes: 2

Variatus
Variatus

Reputation: 14383

Please try the code below. It takes a slightly different approach because it looks for "---- " instead of the "a" or "an".

Sub ConditionalReplace()
    ' 10 Jan 2018

    Dim Pos As Long
    Dim n As Integer

    With Selection
        .HomeKey Unit:=wdStory
        .Find.Text = "---- "

        Do While .Find.Execute = True
            Pos = .Start + 1
            .Collapse wdCollapseStart
            .MoveStart wdWord, -1
            If (StrComp(Trim(.Text), "a", vbTextCompare) = 0) Or _
               (StrComp(Trim(.Text), "an", vbTextCompare) = 0) Then
               .Delete
               n = n + 1
            End If
            .SetRange Pos, ActiveDocument.Characters.Count
        Loop
        .HomeKey Unit:=wdStory
    End With
    MsgBox n & " replacements were made."
End Sub

In order to look for another marker, for example, a string consisting of 12 underscores, modify the line .Find.Text = "---- " to become

.Find.Text = "____________"

If you can't be sure how many underscores there will be consider the code snippet below which will find occurrences of six underscores followed by any other text including, but not limited to, another 6 or 4 underscores.

.Find.MatchWildcards = True
.Find.Text = "______*"

Upvotes: 1

Related Questions