Word 2013中的正则表达式模式

时间:2015-09-28 08:51:51

标签: regex vba ms-word word-vba word-2013

我有一个word文档,其中包含6个系列的数字(纯文本,未编号的样式),如下所示:

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

这种模式已经重复了六次。如何在括号前使用正则表达式并序列化所有数字,以便它们以1开头,最后以120结束?

1 个答案:

答案 0 :(得分:0)

您可以使用VBA - 将其添加到ThisDocument模块:

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

您可以通过点击代码内部的任意位置并点击"播放"来运行它。 VBA IDE中的按钮。