使用宏在文档中反转数字

时间:2016-05-11 07:39:55

标签: vba ms-word ms-office

我想写一个宏来查找数字并在文档中反转它们 例如,将123456转换为654321
我写这个宏但它不起作用:

Function inverter(Numbers)
Dim Num As Long
Dim inverted As Long
Num = Numbers
Do Until Num >= 1
    remainder = Num Mod 10
    Num = Num / 10
    inverted = inverted * 10 + remainder
Loop
inverter = inverted
End Function
Sub invert()
Dim a As Long
    Selection.GoTo What = wdGoToLine, Which = wdGoToFirst
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
           .Text = "([!0-9])([0-9]@)([!0-9])"
           .Replacement.Text = "\1" & a="\2" inverter(a) & "\3"
           .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 Replace:=wdReplaceAll
    End With
End Sub

当我编译它时返回此错误:

---------------------------
Microsoft Visual Basic for Applications
---------------------------
Compile error:

Expected: end of statement
---------------------------
OK   Help   
---------------------------

1 个答案:

答案 0 :(得分:2)

这条线对我来说没有意义

.Replacement.Text = "\1" & a="\2" inverter(a) & "\3"

这似乎是分配,逻辑评估和"错误"

的组合

我无法找到您需要的批量替换解决方案;所以我的建议在这里:

我已将Invertor更改为使用字符串,因为Invertor1而不是1000返回0001(可能不会考虑在Word RegEx)

Function Inverter2(nb As String) As String
    Dim bn As String
    For i = 1 To Len(nb)
        bn = Mid(nb, i, 1) & bn
    Next i
    Inverter2 = bn
End Function

这是您的invert已更改

Sub invert()
Dim a As Long
    Selection.GoTo What = wdGoToLine, Which = wdGoToFirst
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
           .Text = "([!0-9])([0-9]@)([!0-9])"
           '.Replacement.Text = "\1" & a="\2" inverter(a) & "\3"
           .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 Replace:=wdReplaceOne
           While .Execute
               Selection.Text = Inverter2(Selection.Text)
           Wend
    End With
    Selection.GoTo What = wdGoToLine, Which = wdGoToFirst
End Sub

我删除了.Wrap = wdFindContinue,因为文本将被反转两次以保持相同

我也删除了您的替代品并逐一进行。