1
votes

I'm trying to create a macro in word to find particular cells in a table and replace certain strings there. For example:

(word1 or word2 or word3).ab,ti.

Should be replaced by

word1[TIAB] or word2[TIAB] or word3[TIAB]

So, what I've done so far is a simple replaceAll to delete the initial brackets and replace the suffix ").ab,ti." by "[TIAB]. But that doesn't append the endings to word1 and word2, of course.

    Sub Makro6()
'
' Makro6 Makro
'
'
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = ".ab,ti."
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

I guess what I need is to embed a loop in the replaceAll sub, which runs from the first position to the end of the current row and replaces the string " or " by "[TIAB] or ". However, I'm completely new to VBA so I somehow can't figure out how to do this. Any suggestions?

Thanks for your help! Leni

1

1 Answers

3
votes

This code performs the actions you want:

Sub Makro6()

  Dim maxCount, curCount As Integer

  maxCount = 3
  curCount = 0
  Do
    curCount = curCount + 1
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = Chr(40) & "word" & curCount & Chr(41) & ".ab,ti."
        .Replacement.Text = "word" & curCount & "[TIAB]"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = False
        .Execute Replace:=wdReplaceAll
    End With
  Loop While (curCount < maxCount)

End Sub

Note that I had to rely on ASCII codes (Chr(40) & Chr(41)) to account for the parenthesis because surprisingly (at least, for me), the macro wasn't able to find the target string. I did some tests and the problem only happens with parenthesis followed by another character (?!).