带有多个查找/替换选项的 Word VBA 宏仅在选择包含第一个 F/R 选项时才适用于单字选择

问题描述 投票:0回答:1

我创建了一系列宏来选择下一个单词,忽略空格和标点符号,并根据多个查找/替换选项替换单词。我实际上有 12 个宏,都是基于这个原理的。

我有这些宏的更长、更臃肿的版本,多年来一直运行良好,但我现在正在寻求简化和修剪它们,使它们不那么臃肿。这些宏分为四组,每组三个,每组对不同的文本字符串执行相同的功能:第一个宏替换单个单词选择,第二个宏替换一行上的所有“查找”,第三个宏替换所有“在(用户选择的)选择中找到“。

到目前为止,我的单字宏正在工作 - 有点 - 但前提是所选单词是查找字符串中的第一个单词:

这是十月的第一

当我的光标位于“the”上时,宏会将“first”替换为“1st”。但是,如果所选单词是任何其他序数词(第二个到第九个),则光标最终会位于序数词的开头 - 不会出现错误消息。

对于我做错了什么有什么建议吗?预先感谢您的帮助!

凯伦:)

Sub ReplaceNextOrdinal()

Dim StrFind As String, StrRepl As String
    
StrFind = "first,second,third,fourth,fifth,sixth,seventh,eighth,ninth"
StrRepl = "1st,2nd,3rd,4th,5th,6th,7th,8th,9th"

        Selection.MoveRight Unit:=wdWord, Count:=1
        
        With Selection.Find
            .Text = Split(StrFind, ",")
            .Replacement.Text = Split(StrRepl, ",")
            .IgnorePunct = True
            .IgnoreSpace = True
            .Execute Replace:=wdReplaceOne
        End With

End Sub
vba ms-word
1个回答
0
投票

您缺少 Split() 数组上的循环

Sub ReplaceNextOrdinal()
    'use const for fixed values
    Const StrFind = "first,second,third,fourth,fifth,sixth,seventh,eighth,ninth"
    Const StrRepl = "1st,2nd,3rd,4th,5th,6th,7th,8th,9th"
    
    Dim arrF, arrR, i As Long
    
    arrF = Split(StrFind, ",")
    arrR = Split(StrRepl, ",")
    
    Selection.MoveRight unit:=wdWord, Count:=1
    Selection.Expand unit:=wdWord 'select the word
    
    Debug.Print "Checking: " & Selection.Text
    For i = LBound(arrF) To UBound(arrF)
        With Selection.Find
            .Text = arrF(i)
            .MatchWholeWord = True
            .Replacement.Text = arrR(i)
            .IgnorePunct = True
            .IgnoreSpace = True
            If .Execute(Replace:=wdReplaceOne) Then Exit For  'found one!
        End With
    Next i
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.