regexvbams-wordword-2013

Regex pattern in Word 2013


I have a word document which contains 6 series of numbers (plain text, not numbered style) as following:

1) blah blah blah
2) again blah blah blah
.
.
.
20) something

And this pattern has been repeated six times. How can I used Regex and serialise all numbers before parentheses so that they start with 1 and end up with 120?


Solution

  • You can use VBA - add this to the ThisDocument module:

    Public Sub FixNumbers()
        Dim p As Paragraph
        Dim i As Long
        Dim realCount As Long
        realCount = 1
        Set p = Application.ActiveDocument.Paragraphs.First
    
        'Iterate through paragraphs with Paragraph.Next - using For Each doesn't work and I wouldn't trust indexing since we're making changes
        Do While Not p Is Nothing
            digitCount = 0
            For i = 1 To Len(p.Range.Text)
                'Keep track of how many characters are in the number
                If IsNumeric(Mid(p.Range.Text, i, 1)) Then
                    digitCount = digitCount + 1
                Else
                    'We check the first non-number character we find to see if it is the list delimiter ")" and we make sure that there were some digits before it
                    If Mid(p.Range.Text, i, 1) = ")" And digitCount > 0 Then
                        'If so, we get rid of the original number and put the correct one
                        p.Range.Text = realCount & Right(p.Range.Text, Len(p.Range.Text) - digitCount) 'It's important to note that a side effect of assigning the text is that p is set to p.Next
    
                        'realCount holds the current "real" line number - everytime we assign a line, we increment it
                        realCount = realCount + 1
                        Exit For
                    Else
    
                        'If not, we skip the line assuming it's not part of the list numbering
                        Set p = p.Next
                        Exit For
                    End If
                End If
            Next
        Loop
    End Sub
    

    You can run it by clicking anywhere inside of the code and clicking the "play" button in the VBA IDE.