VBA [classes] - how to access a previously instanc

2019-07-06 04:00发布

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 for 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.

标签: oop vba
2条回答
【Aperson】
2楼-- · 2019-07-06 04:36

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'.

查看更多
forever°为你锁心
3楼-- · 2019-07-06 04:47

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
查看更多
登录 后发表回答