反转文档中的所有数字

时间:2015-10-12 09:38:55

标签: vba ms-word word-vba

我有一个Word文档,我想要反转其中的所有数字(例如:将123456转换为654321)。

我找到了这个方法:

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  

但是这种方法适用于第一个数字而忽略其他数字。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

它仅适用于第一次出现,因为您正在使用.Execute参数执行wdReplaceOne。您可以使用wdReplaceAll参数替换所有匹配项,但之后您将所有参数替换为相同的值。

我建议反复运行Find并单独更换范围。 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

请注意,跟踪索引是必要的,以防止Find在最后一次出现时无限循环。