CallByName function can help you. Suppose your project has several class modules: clsSample0 , clsSample1 and clsSample2 . Add a new class module named clsSpawner , which lists all target classes as public variables with the same name and is declared with the New keyword:
Public clsSample0 As New clsSample0 Public clsSample1 As New clsSample1 Public clsSample2 As New clsSample2
Add the Function Spawn() code to the standard module:
Function Spawn(sClassName) As Object Set Spawn = CallByName(New clsSpawner, sClassName, VbGet) End Function
Test it with the following code:
Sub TestSpawn() Dim objSample0a As Object Dim objSample0b As Object Dim objSample1 As Object Dim objSample2 As Object Set objSample0a = Spawn("clsSample0") Set objSample0b = Spawn("clsSample0") Set objSample1 = Spawn("clsSample1") Set objSample2 = Spawn("clsSample2") Debug.Print TypeName(objSample0a) ' clsSample0 Debug.Print TypeName(objSample0b) ' clsSample0 Debug.Print objSample0a Is objSample0b ' False Debug.Print TypeName(objSample1) ' clsSample1 Debug.Print TypeName(objSample2) ' clsSample2 End Sub
How it works? The Spawn function creates an instance of clsSpawner and calls an instance of clsSpawner to return the requested property, but in fact an instance of clsSpawner creates a new instance of the target class due to the declaration with the keyword New and returns the link.
omegastripes
source share