0

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

你知道如何优化这两个程序(我使用 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
4

1 回答 1

0

我不完全确定您要做什么,因为您的代码确实有效。当您说optimize时,您是在问是否有更快的方法来做到这一点,还是在问您的代码是否可以缩短?我看不出您在开始时设置的尺寸有任何原因,所以如果您只是在寻找更短的代码,您可以使用以下内容:

    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
于 2012-12-14T23:39:43.120 回答