vba 嵌套语句层次结构
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41815258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nested With Statement hierarchy
提问by Rdster
I've come across this a couple of times recently and was just curious if there was an easier way to do this...
我最近遇到过几次这个问题,只是想知道是否有更简单的方法来做到这一点......
With Activeworkbook
'Do Stuff
With .Sheets(1)
'More stuff Done
'...
'But now I need to refer to or pass the Sheet in the last With Statement
SomeFunctionAnswer = SomeFunction Activeworkbook.Sheets(1)
End With
'Yet more stuff Done
End With
Does it have to be fully written out, or is there some way of notating it that makes it easier/cleaner? Perhaps there is some sort of property or method to pass itself for just this instance? What about referring to a property or method from the higher With?
它是否必须完全写出,或者是否有某种方式可以使它更容易/更干净?也许有某种属性或方法可以为这个实例传递自己?从更高的 With 引用属性或方法怎么样?
SomeFunctionAnswer = SomeFunction .Self '???
'OR
SomeFunctionAnswer = SomeFunction .Parent.Name '???
Hope that makes sense...
希望这是有道理的...
回答by A.S.H
The answer is a plain and simple No No.
答案是简单明了的 No No。
The With
clause facilitates the access to the members and methods of its subject, but it does not provide any facility to reference the subject itself. When that's needed, you have to write the name the object completely or refer to it by other means.
该With
子句有助于访问其主题的成员和方法,但它不提供任何引用主题本身的便利。当需要时,您必须完整地写出对象的名称或通过其他方式引用它。
When accessing methods and members of an object that is the subject of an outerWith
clause, again, you need to name it completely. The inner With
, and for the whole of its scope,completely hides the outer With
.
当访问作为外部With
子句主题的对象的方法和成员时,同样需要完全命名它。内部With
,以及其整个范围,完全隐藏了外部With
。
Therefore, the way you wrote your code is the correct way to do it.
因此,您编写代码的方式是正确的方式。
回答by SJR
Perhaps easier to just assign to a variable, but here is one approach:
也许只分配给变量更容易,但这是一种方法:
With Activeworkbook
'Do Stuff
With .Sheets(1)
'More stuff Done
'...
'But now I need to refer to or pass the Sheet in the last With Statement
SomeFunctionAnswer = SomeFunction Sheets(.name)
End With
'Yet more stuff Done
End With
回答by J. Garth
You could move it out of the inner with and into the outer with. Then you could drop the Activeworkbook qualification.
您可以将其从内部移出并移入外部。然后您可以放弃 Activeworkbook 资格。
With Activeworkbook
'Do Stuff
With .Sheets(1)
'More stuff Done
'...
End With
SomeFunctionAnswer = SomeFunction .Sheets(1)
'Yet more stuff Done
End With