【问题标题】:Is it possible to use the temporary object of a with-statement as a parameter for a function?是否可以使用 with 语句的临时对象作为函数的参数?
【发布时间】:2024-05-03 04:30:02
【问题描述】:

我在 VBA 中使用这样的 with 语句:

With New MSXML2.DOMDocument60
    'Some statements
end with

我有一个这样的子:

Private Sub anyfunction(ByVal par_document As MSXML2.DOMDocument60)

end sub

有没有办法使用临时对象作为 anyfunction 的参数,或者我必须使用“Dim”创建一个变量才能使用 anyfunction?

【问题讨论】:

  • 你指的是什么临时变量?如果您可以参考它,那么您可以通过它。我不认为你有任何方法可以参考它,尽管Me 可能是一个自然的猜测。
  • 由 with 语句创建的(MSXML2.DOMDocument60 类型)。
  • 那是一个对象,不是一个变量
  • 我改了问题。
  • 这是一个有趣的问题。我认为答案是否定的,但即使答案是肯定的,我仍然会使用变量来清楚地说明。

标签: vba with-statement


【解决方案1】:

如果对象提供了对其自身的引用,请使用它。对于MSXML2.DOMDocument60,您可以使用.SelectSingleNode("/") 或使用引用父对象的子对象。 (例如.documentElement.ownerDocument.childNodes(0).parentNode,但他们需要加载一个 XML 文档。) 或相反(父对子)为Dao.Recordsetuse.Parent.RecordSets(.Name)

With New MSXML2.DOMDocument60
    .Load("xmlfile")
    anyfunction(.SelectSingleNode("/"))
end with

【讨论】:

  • 它回答了这个问题吗? OP想通过整个DOMDocument60,但他不能通过With
  • @JohnyL .SelectSingleNode("/")返回MSXML2.DOMDocument60。测试使用Set doc = New MSXML2.DOMDocument60; If doc.SelectSingleNode("/") Is doc then Debug,Print "Same object".
最近更新 更多