查找。执行并显示确认对话框

乔·莫宁

我在Visual Basic中写了一个宏(我知道),以在Microsoft Word中解析文档。这是我要实现的工作流程:

  • 在文档中搜索一个字符串(相当于Edit > Find > Find...)。
  • 询问用户是否要将匹配的字符串替换为另一个字符串(等同于Edit > Find > Replace... > Replace,但是在执行替换之前先出现确认对话框)。
  • 如果是,请进行更换。如果不是,请转到下一场比赛。

我可以找到并替换为该Find.Execute方法

Set myRange = ActiveDocument.Content 
myRange.Find.Execute FindText:="hi", _ 
    ReplaceWith:="hello", Replace:=wdReplaceAll

但是我不确定执行替换之前如何提示用户。

共产国际

您可以在消息框中提示,然后测试返回值并根据该值执行替换:

Private Sub PromptForReplace()

    Dim myRange As Range

    Set myRange = ActiveDocument.Content
    myRange.Find.ClearFormatting
    myRange.Find.MatchWildcards = True

    Dim cached As Long
    cached = myRange.End
    Do While myRange.Find.Execute("hi")
        myRange.Select
        If MsgBox("Replace " & myRange.Find.Text & "?", vbYesNo) = vbYes Then
            myRange.Text = "hello"
        End If
        myRange.Start = myRange.Start + Len(myRange.Find.Text)
        myRange.End = cached
    Loop

End Sub

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章