coldbreeze16
coldbreeze16

Reputation: 87

MS Word VBA macro to search and replace (Regex)

Suppose a word file contains

ab{cdefg{hij{k

And I want { to be moved one place to the right like

abc{defgh{ijk{

I need to make an array with all characters then run a loop with Regex search and replace

search:

({)(array[index])

replace:

$2$1

Plain Regex without loop won't work because I'm dealing with Indic text which have complex characters. I've done this on JavaScript and ExtendScript in inDesign, but I've no clue about VB. Can anyone please help?

Upvotes: 0

Views: 1804

Answers (1)

Dirk Vollmar
Dirk Vollmar

Reputation: 176159

This can be done using a Word wildcard search-and-replace:

With ActiveDocument.Range.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .ClearAllFuzzyOptions
    .Text = "(\{)(?)"           ' find opening brace followed by a single character
    .Replacement.Text = "\2\1"  ' swap positions
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchByte = False
    .MatchAllWordForms = False
    .MatchSoundsLike = False
    .MatchFuzzy = False
    .MatchWildcards = True
End With
ActiveDocument.Range.Find.Execute Replace:=wdReplaceAll

Upvotes: 1

Related Questions