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

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

我创建了一系列宏来选择下一个单词,忽略空格和标点符号,并根据多个查找/替换选项替换单词。我实际上有 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
2个回答
1
投票

您缺少 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

0
投票

为您提供更复杂的东西。下面的代码适用于任何选定的范围,允许您一次处理多个序数,并为它们加上上标。按照编码,您也可以包含大于 10 的序数。

Sub ReplaceNextOrdinal()
Application.ScreenUpdating = False
Dim ArrFnd As Variant, ArrRep As Variant, RngFnd As Range, i As Long
'Array of Find expressions
ArrFnd = Array("first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth")
ArrRep = Array("1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th")
Set RngFnd = ActiveDocument.Range(Selection.Words.First.Start, Selection.Words.Last.End)
For i = 0 To UBound(ArrFnd)
  With RngFnd.Duplicate
    With .Find
      .ClearFormatting
      .Replacement.ClearFormatting
      .IgnorePunct = True
      .IgnoreSpace = True
      .MatchWholeWord = True
      .Text = ArrFnd(i)
    End With
    Do While .Find.Execute
      If .InRange(RngFnd) Then
        .Text = ArrRep(i)
        .Start = .Characters.Last.Previous.Start
        .Font.Superscript = True
      Else
        Exit Do
      End If
    Loop
  End With
Next i
Application.ScreenUpdating = True
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.