Create a new object using the text name of the class

excel, vba

Solution

You can use metaprogramming to do this, although it does seem like quite a hack. Here is an example that uses a couple of helper functions (omitted for brevity):

Public Function CreateInstance(typeName As String) As Object
    Dim module As VBComponent
    Set module = LazilyCreateMPCache()

    If Not FunctionExists(typeName, module) Then
        Call AddInstanceCreationHelper(typeName, module)
    End If

    Dim instanceCreationHelperName As String
    instanceCreationHelperName = module.name & ".GetInstanceOf" & typeName
    Set CreateInstance = Application.Run(instanceCreationHelperName)
End Function

Sub AddInstanceCreationHelper(typeName As String, module As VBComponent)
   Dim strCode As String
   strCode = _
   "Public Function GetInstanceOf" & typeName & "() As " & typeName & vbCrLf & _
       "Set GetInstanceOf" & typeName & " = New " & typeName & vbCrLf & _
   "End Function"
   Call AddFunction(strCode, module)
End Sub

Problem

Is there a way to set an object to the new instance of a class by using the text name of the class? I will have a library of classes, and depending on some other variable, I want to get one of these classes at runtime. E.g. I have "CTest1", "CTest2", "CTest3" I would have function similar to the below ``` Function GetTestClass(lngClassNo as long) as Object Dim strClassName as String strClassName = "CTest" & CStr(lngClassNo) Set GetTestClass = New instance of class(strClassName) End Function ```

Original source