vendredi 23 août 2019

Dynamically choose class from string

I'm trying to be able to get an instance of a class based on a passed string ClassName without a bunch of IFs.

Class - ICLass

Public Function DoSomething()
End Function

Class - Class1

Implements IClass
Public Function iclass_dosomething()
    Debug.Print "Done from class1"
End Function

Class - Class2

Implements IClass
Public Function iclass_dosomething()
    Debug.Print "Done from class2"
End Function

Module1 - test module

Sub GetInstanceOf(ByVal s As String, ByRef Result As Object)
    Dim vbComp As Object
    Dim CodeString As String
    Set vbComp = ThisWorkbook.VBProject.VBComponents.Add(1)
    CodeString = "Sub foo(ByRef Result as Object)" & vbCrLf & _
            "Set Result = New " & s & vbCrLf & _
        "End Sub"
    vbComp.CodeModule.AddFromString CodeString

    Application.Run vbComp.Name & ".foo", Result
    ThisWorkbook.VBProject.VBComponents.Remove vbComp
End Sub

Sub Testing()
    Dim ClassName As String
    ClassName = "Class2"
    'ClassName = "Class1"
    Dim c As IClass
    Set c = New Class1
    GetInstanceOf ClassName, c
    c.DoSomething
End Sub

I'm getting

Done from class1

I'm expecting

Done from class2





Aucun commentaire:

Enregistrer un commentaire