使用VBA在Microsoft Word中搜索并替换为用户决定

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

我对编写VBA代码还很陌生,但是我想解决以下问题:

借助宏记录器,我已经可以解决部分问题。我可以搜索不同的文本,并替换其中的ALL。但是,我想在WORD文档中搜索文本,然后让用户决定是否要更改此文本。这是一个示例:我想搜索“ m2”并将文本更改为“m²”。但是“ m2”也可能是商品编号或类似内容的一部分,因此在这里不能进行任何更改。

但是我的GOOGLE搜索未返回任何结果,因为搜索“搜索”没有提供解决方法😉

我的第一部分代码如下:

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
    .text = "m2"
    .replacement.text = "m²"
    Forward = True
    .wrap = wdFindContinue
    .format = False
    MatchCase = True
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll

然后我的VBA代码中有数十个,一个接一个。

我对任何帮助都很高兴。

Peter

vba ms-word word-vba
2个回答
2
投票

例如:

Sub Demo()
Dim StrFnd As String, StrRep As String, Rslt
StrFnd = InputBox("Find Text")
StrRep = InputBox("Replacement Text")
With ActiveDocument.Range
    With .Find
      .ClearFormatting
      .Replacement.ClearFormatting
      .Text = StrFnd
      .Replacement.Text = ""
      .MatchWholeWord = True
      .Forward = True
      .Format = False
      .MatchCase = True
      .Wrap = wdFindStop
      .Execute
    End With
    'Replace the found text, asking first
    Do While .Find.Found
      .Duplicate.Select
      Rslt = MsgBox("Replace this instance of:" & vbCr & _
        StrFnd & vbCr & "with:" & vbCr & _
        StrRep, vbYesNoCancel)
      If Rslt = vbCancel Then Exit Sub
      If Rslt = vbYes Then .Text = StrRep
      .Collapse wdCollapseEnd
      .Find.Execute
    Loop
  End With
End Sub

0
投票

够了吗?

Private Sub ChangeTextWithAsking()
    Dim res As VbMsgBoxResult
    Selection.Find.Execute FindText:="m2"
    Do While Selection.Find.Found
        res = MsgBox("Change?", vbYesNoCancel)
        Select Case res
            Case vbYes
                Selection.Delete
                Selection.TypeText "m"
                Selection.Font.Superscript = True
                Selection.TypeText "2"
            Case vbNo
                Selection.MoveRight
        Case Else
            Exit Do
        End Select
        Selection.Find.Execute
    Loop
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.