代码之家  ›  专栏  ›  技术社区  ›  Jonathan

VBA中“with”子句的恼人问题

  •  3
  • Jonathan  · 技术社区  · 14 年前

    我用这个函数替换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
    

    但是。。。我不知道为什么如果我这样重写函数,它就会停止工作。没有错误或警告,但没有进行替换。

    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
    

    有人能解释一下这两个片段的区别是什么,或者为什么第二个片段不能正常工作? 谢谢!

    2 回复  |  直到 14 年前
        1
  •  7
  •   Dick Kusleika    14 年前

    Find属性在每次调用Find对象时返回该对象。所以在你的第二段代码中

    1. 创建查找对象并设置其文本属性
    2. 创建新的Find对象并设置其替换.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
    
        2
  •  1
  •   Vicky    14 年前

    这真的是你的代码的剪切和粘贴吗?这两种方法应该是一样的。你确定没有其他事情像奇数行结束?

    (我在第一个例子中注意到 End If 缩进不正确,但我怀疑与此有关)