Change how to replace based on captured values in Find's RegEx RRS feed

  • Question

  • I am working on bilingual documents (Arabic-English), The two languages have different directions (RTL and LTR respectively) which makes working with it a bit more challenging.

    I am writing a macro to change numbers of the form (x.x) to (x,x), a change in the comma.

    now here is the problem, sometimes the two numbers are switched when I do the replace, for example: x.y becomes y,x.

    after some debugging it turned out that sometimes this (.) in the first form is an Arabic character and when it is replaced with (,) which is an English one it is causing this change in order.

    so I want to do is the following, but I don't know how to translate it to VBA:  

        1- look for a match to the expression ([0-9]{1, }).([0-9]{1, }) 'two numbers with a dot in between
        2- if the dot in between is English, replace as follows \1,\2  'no change  
        3- else if it is Arabic, replace as follows \2,\1

    Thanks for your help

    here is the current version of the macro, it is a recorded macro. I just added the if else statement.

    Sub fixComma()
    ' fixComma Macro
       If (Selection.Start <> Selection.End) Then
        Selection.Find.Replacement.LanguageID = wdEnglishUS
        With Selection.Find
            .Text = "([0-9]).([0-9])"
            .Replacement.Text = "\1,\2"
            .Forward = True
            .Wrap = wdFindStop
            .Format = True
            .MatchCase = False
            .MatchWholeWord = False
            .MatchKashida = False
            .MatchDiacritics = False
            .MatchAlefHamza = False
            .MatchControl = False
            .MatchByte = False
            .MatchAllWordForms = False
            .MatchSoundsLike = False
            .MatchWildcards = True
        End With
        Selection.Find.Execute Replace:=wdReplaceAll
          MsgBox "Nothing is selected, Macro terminated"
        End If
    End Sub

    Or Maybe I am taking the wrong approach here and I should go through the paragraphs myself and check for a match for the RegEx instead of using Find and Replace ?
    Thursday, August 20, 2015 7:02 AM


  • Hi Tahawi

    It seems to me a couple of approaches are possible.

    Looking at your current code, it might be simplest to perform two sets of "Find" actions: one for searching text formatted as English, the other searching for text formatted as Arabic?

    The other, more usual way when you have to handle something that can't be done by the Find functionality, is to put the Find in a loop. Everytime Find.Execute returns True (meaning it's found a match) your code performs the required actions, then it loops and Find is run again. In this case, it is not possible to use Replace, the code would have to parse what's been found and switch the numbers and apply the language formatting.

    Cindy Meister, VSTO/Word MVP, my blog

    Thursday, August 20, 2015 4:22 PM