Is it possible to send and store a Type reference in VB6/VBA?
-
02-07-2019 - |
Question
I'm working on a VB6 application and I would like to send a Type as a reference and store it in another form. Is this possible?
Sending it is no problem, I just use the ByRef
keyword:
public Sub SetStopToEdit(ByRef currentStop As StopType)
But when I try to use Set to store currentStop
in the receiving module I get the "Object required" error when running the program:
Private stopToEdit As StopTypeModule.StopType
' ... Lots of code
Set stopToEdit = currentStop
StopType
is defined as follows in a Module (not a class module):
Public Type StopType
MachineName As String
StartDate As Date
StartTime As String
Duration As Double
End Type
Is it possible to store the sent reference or do I have to turn StopType
into a class?
While just setting a local variable works:
stopToEdit = currentStop
When stopToEdit
is later changed the change is not visible in the variable sent to SetStopToEdit
.
Solution
You need to refactor it into a class.
OTHER TIPS
What is StopType? How is it defined? Is a Type the VB6-Record stuff? If so (and if possible), you should redefine it as a class - and only use those, as you will run into problems with Collections otherwise.
Try dropping the Set
Keyword - Strings, Integers and Numbers, but if I remember correctly, also Records, are not Set, they are Let, but that is implicit in the assignement:
stopToEdit = currentStop
EDIT: If you want to change the passed in (ByRef) record, do a manual element for element copy instead of reassigning the whole thing - that should do the trick.
At the same time: DON'T! ByRef (sadly in VB the default) is not so very cool (to paraphrase my son). Try to design your functions so they don't change arguments passed in - this is what you have a return value for...
The confusion here is that a StopType is not a reference like an object, but behaves more like an in built type such as LONG. When you do:
stopToEdit = currentStop
You are only taking a copy of currentStop. If you subsequently change stopToEdit, you'll need to copy it back:
currentStop = stopToEdit
That way the value will be passed back out of the Sub.