Nested With Statement hierarchy

让人想犯罪 __ 提交于 2020-01-03 08:07:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!