VBA中"with"子句令人讨厌的问题

Jon*_*han 3 ms-access vba

我正在使用此函数来替换word文档中的某些字符串.这个功能很好用

Sub reemplazar(doc As Word.Document, after As String, before As String, replaceall As Boolean)
    With doc.Content.Find
        .Text = after 
        .Replacement.Text = before 
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = True
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        If replaceall Then
            .Execute replace:=wdReplaceAll
        Else
            .Execute replace:=wdReplaceOne
    End If
    End With
End Sub
Run Code Online (Sandbox Code Playgroud)

但是......我不知道为什么如果我以这种方式重写函数它就会停止工作.没有错误或警告,但没有更换.

Sub reemplazar(doc As Word.Document, after As String, before As String, replaceall As Boolean)
    doc.Content.Find.Text = after 
    doc.Content.Find.Replacement.Text = before 
    With doc.Content.Find
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = True
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        If replaceall Then
            .Execute replace:=wdReplaceAll
        Else
            .Execute replace:=wdReplaceOne
        End If
    End With
End Sub
Run Code Online (Sandbox Code Playgroud)

有人可以解释这两个片段之间有什么区别,或者为什么第二个片段不能正常工作?谢谢!

Dic*_*ika 7

每次调用Find属性时,Find属性都会返回一个Find对象.所以在你的第二个代码片段中,你是

  1. 创建Find对象并设置其Text属性
  2. 创建一个新的Find对象并设置其Replacement.Text属性
  3. 创建第三个Find对象并设置一堆其他属性并执行

最后执行的Find对象没有设置Text或Replacement.Text属性.如果你想以这种方式使用它,你可以创建一个像这样的对象变量

Sub reemplazar(doc As Word.Document, after As String, before As String, replaceall As Boolean)

    Dim fnd As Find

    Set fnd = doc.Content.Find

    fnd.Text = after
    fnd.Replacement.Text = before
    With fnd
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = True
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        If replaceall Then
            .Execute Replace:=wdReplaceAll
        Else
            .Execute Replace:=wdReplaceOne
        End If
    End With
End Sub
Run Code Online (Sandbox Code Playgroud)