优化查找和替换MS-Word VBA脚本

时间:2012-11-26 10:24:08

标签: ms-word wildcard replace word-vba

我写了一个宏,用于替换三个空格中第一个的格式,后跟一个带蓝色字体数字的字符串,另一个用于替换括号之间的空格,后跟一个字符串。

你知道如何优化这两个程序(我使用搜索的通配符并替换MS-Word的对话,但是猜测在VBA中使用它是相当尴尬的。)?

我的宏:

Sub replace_3spaces()

Dim str_after As String
Dim re_number As Integer

str_after = "normal"
re_number = "1"

    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "([^s]{3})" & "(" & str_after & ")"
        .Replacement.Text = "§§§\2"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll

    Selection.Find.ClearFormatting
    Selection.Find.Replacement.Font.ColorIndex = wdBlue
    With Selection.Find
        .Text = "§§§"
        .Replacement.Text = re_number & " "
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

1 个答案:

答案 0 :(得分:0)

我不完全确定你要做什么,因为你的代码工作。当您说优化时,您是在问是否有更快捷的方法,或者您是否在询问您的代码是否可以缩短?我看不出你在开始时设置尺寸的任何原因,所以如果你只是寻找更短的代码,你可以使用以下内容:

    With Selection.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = "([^s]{3})(normal)"
        .Replacement.Text = "§§§\2"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchWildcards = True
        .Execute Replace:=wdReplaceAll
        .Forward = False
        .ClearFormatting
        .Replacement.Font.ColorIndex = wdBlue
        .Format = True
        .Text = "§§§"
        .Replacement.Text = "1 "
        .Execute Replace:=wdReplaceAll
    End With

基于你有这些尺寸的事实,并且你使用了其中一个的数字,我不禁想到你实际上是在尝试创建一个编号系统,其中每个实例都有一个数字。如果是这种情况,请使用以下代码:

Dim str_after, oldColor As String
Dim re_number As Integer

str_after = "normal"
re_number = "1"

    Selection.HomeKey unit:=wdStory
    With Selection.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = "([^s]{3})" & "(" & str_after & ")"
        .Replacement.Text = "§§§\2"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = True
    End With
        While Selection.Find.Execute
            oldColor = Selection.Font.Color
            Selection.Font.Color = wdColorBlue
            Selection.TypeText Text:=re_number & " "
            Selection.Font.Color = oldColor
            Selection.TypeText Text:=str_after
            re_number = re_number + 1
        Wend