开发者

VBA [classes] - how to access a previously instanciated instance of a class in another sub

I've created the instance "Lassie" of the class "Dog" within a particular sub in my program. I have also given it some useful properties, such as Lassie.Age = 7 and Lassie.HeelCapability = False.

Now I would like to access another sub and change the Lassie.HeelCapability to True. How do I go about defining the instance "Lassie" within this new sub so it can be worked with?

All the code I have come accross goes like this:

Dim Lassie As classDog

Set Lassie = New classDog

Essentially what I am looking f开发者_JS百科or is a way to import the existing instance "Lassie" into another sub, without using the keyword "New" and thereby creating a new "Lassie" (without all the properties previously given).

The errormessages I have been receiving tell me either "object required" or "object variable or with block variable not set".

Surely there is a way to do this.

Thanks in advance.


You will need to pass 'Lassie' as a parameter to your other sub.

public sub DeclareSub()
  Dim Lassie as classDog
  Lassie = new classDog

  OtherSub Lassie
end sub

public sub OtherSub(ByRef dog as classDog) 

end sub

The variable 'dog' in the subroutine 'OtherSub' refers to the same object instance as the variable 'Lassie' from 'DeclareSub'.


Pass the object in ByRef to your new Subroutine.

Sub ChangeHeel(ByRef olassie As classDog)
    'change the object here, and it will be changed in the calling sub
    olassie.HeelCapability = True
End Sub
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜