问题
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?
SomeFunctionAnswer = SomeFunction .Self '???
'OR
SomeFunctionAnswer = SomeFunction .Parent.Name '???
Hope that makes sense...
回答1:
The answer is a plain and simple 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.
When accessing methods and members of an object that is the subject of an outer With clause, again, you need to name it completely. The inner With, and for the whole of its scope, completely hides the outer With.
Therefore, the way you wrote your code is the correct way to do it.
回答2:
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
回答3:
You could move it out of the inner with and into the outer with. Then you could drop the Activeworkbook qualification.
With Activeworkbook
'Do Stuff
With .Sheets(1)
'More stuff Done
'...
End With
SomeFunctionAnswer = SomeFunction .Sheets(1)
'Yet more stuff Done
End With
来源:https://stackoverflow.com/questions/41815258/nested-with-statement-hierarchy