Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

oop

vba

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.

like image 489
Stinn Avatar asked Dec 21 '25 06:12

Stinn


1 Answers

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

like image 61
Chris Flynn Avatar answered Dec 23 '25 18:12

Chris Flynn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!