gpt4 book ai didi

ms-access - VBA 中 "with"子句的烦人问题

转载 作者:行者123 更新时间:2023-12-01 09:38:01 24 4
gpt4 key购买 nike

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

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

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

最佳答案

每次调用 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

关于ms-access - VBA 中 "with"子句的烦人问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4248026/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com