YFeizi
YFeizi

Reputation: 1528

Reverse all numbers in document

I have a Word document and I want to reverse all numbers in it (for example: convert 123456 to 654321).

I find this method :

Sub Reverser()
    Dim Finder As String
    Dim Number As String
    Dim i As Integer
    With Selection.Find
        .Text = "[!0-9][0-9]{5}[!0-9]"
        .Replacement.Text = StrReverse(Selection)
        .Forward = True: .Wrap = wdFindContinue: .Format = False: .MatchCase = False: .MatchWholeWord = False: .MatchKashida = False: .MatchDiacritics = False: .MatchAlefHamza = False: .MatchControl = False: .MatchWildcards = True: .MatchSoundsLike = False: .MatchAllWordForms = False
    End With
    Selection.Find.Execute replace:=wdReplaceOne
End Sub  

But this method work for first number and ignore other.

How can I resolve this ?

Upvotes: 1

Views: 43

Answers (1)

DanL
DanL

Reputation: 999

It only works for the first occurrence because you're executing .Execute with the wdReplaceOne parameter. You could replace all occurrences by using a wdReplaceAll parameter, but then you'd replace them all with the same value.

I suggest running a Find repeatedly and replacing the ranges individually. E.g.:

Sub Reverser()
    Dim rngFind As Range
    Dim i As Integer
    i = -1

    Set rngFind = ActiveDocument.Range(0, 0)

    With rngFind.Find
        .Text = "[!0-9][0-9]{5}[!0-9]"
        .Forward = True: .Wrap = wdFindContinue: .Format = False: .MatchCase = False: .MatchWholeWord = False: .MatchKashida = False: .MatchDiacritics = False: .MatchAlefHamza = False: .MatchControl = False: .MatchWildcards = True: .MatchSoundsLike = False: .MatchAllWordForms = False
        .Execute

        Do While .Found And i < rngFind.Start
            rngFind.Text = StrReverse(rngFind.Text)
            i = rngFind.Start
            .Execute
        Loop
    End With
End Sub

Note that keeping track of the index is necessary to prevent Find from looping infinitely on the last occurrence.

Upvotes: 1

Related Questions