Dynamic class declaration options

1778 views vba

I'm trying to have the option for the user to select variable different classes based on an user input. Unit_Alpha and Unit_Beta are two different classes that the user can choose from for the unit. Both Classes have the run() function that takes the same inputs and return value, but they do different calculations. As a result I don't think they can be the same class. When I dim the unit in the select case, visual basic does not like it. Is there a way to allow this or an alternative method?

Thanks in advance.

    Select Case unitsearch.Text
        Case "Alpha"
            Dim unit As New Unit_Alpha
        Case "Beta"
            Dim unit As New Unit_Beta
        Case Else
            MsgBox("no unit properly selected")
            Exit sub
    End Select
    Answer = unit1.run(variables)

answered question

What's the signature for the Run method, and what is unit1?

@sebslaman, please edit the question title: "decoloration" -> "declaration" ...

@MathieuGuindon and example of one run function is: Public Function Run() As Integer Return Form1.d6() ' random number between 1 and 6 End Function

1 Answer


closely sticking to the question I'd propose:

Dim unit As Object
Select Case unitsearch.Text
    Case "Alpha"
        Set unit = New Unit_Alpha
  Case "Beta"
        Set unit = New Unit_Beta
  Case Else
      MsgBox ("no unit properly selected")
      Exit Sub
End Select

posted this

Have an answer?


Please login first before posting an answer.