# MS Word (VBA) / Find Numbers (1,2, & 3 Digits) / Replace with 1,2,3,4,5,6 ...



## KenWit (Apr 2, 2013)

I have a document with numbered sentences.
The numbers are out of sequence.
I'd like to make a macro to find and replace the numbers,
and replace them with an ordered sequence: 1, 2, 3, 4, 5 ...

The text looks like this:

1. John ate an apple. 3. He went to the store. 77. He bought candy. 104. He went home. 5. He played videos.

The best I was able to do was this:

Sub ReNumber()
'
    Dim i As Integer

    j = 0

    For Each w In Documents(ThisDocument).Words

    If IsNumeric(w) Then
    i = i + 1
    End If
    Next w

    For CNT = 1 To i

    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "[0-9]{1,2}"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = True
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute
    Selection.Font.ColorIndex = wdDarkRed

    j = j + 1


    With Selection.Find
    .Replacement.Text = j
    .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = True
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With


    Selection.Find.Execute Replace:=wdReplaceOne

    Next CNT

End Sub

Any suggestions? I basically have given up at this point. 
Thanks!


----------



## Macropod (Apr 2, 2013)

If you configure Word to use its Heading Styles for your numbering (with multi-level list numbering), you can run the following macro:


```
Sub AutoNumber()
 Dim Para As Paragraph, Rng As Range, iLvl As Long
 With ActiveDocument.Range
   For Each Para In .Paragraphs
     Set Rng = Para.Range.Words.First
     With Rng
       If IsNumeric(.Text) Then
         While .Characters.Last.Next.Text Like "[0-9. " & vbTab & "]"
           .End = .End + 1
         Wend
         iLvl = UBound(Split(.Text, "."))
         .Text = vbNullString
         Para.Style = "Heading " & iLvl
       End If
     End With
   Next
 End With
 End Sub
```
With the above code, not only will you get the correct 1, 2, 3, 4, 5 sequence, but you'll also get correct sequences for 1, 1.1, 1.1.1, 1.2, 1.2.1, 2. 2.1, 2.1.1, 2.1.2, 2.1.3 etc.


----------

