I’m writing some VBA code that will communicate with different instruments (signal generator, power meter etc.). For each instrument type, I want the user to be able to select between different instrument models.
My thought was that I could create a class for each model. In the beginning of the code, I want to declare an object to one of these classes. I want to do this to avoid having my code full of “if” and “case”.
I have written this simple sample code and it seem to work without declaration of the object. If I add a declaration, I get error message “Type Mismatch” or “Duplicate declaration in current scope” deepening on where I put the declaration. Is there any downside running the code without declaration or is it any alternative method I can use doing the same thing?
'Dim Inst As InstrumentType1
Sub Test()
Dim i As Integer
i = Worksheets("Sheet1").Range("A1").Value
If i = 1 Then
'Dim Inst As InstrumentType1
Set Inst = New InstrumentType1
Else
'Dim Inst As InstrumentType2
Set Inst = New InstrumentType2
End If
Receive = Inst.SendString("Hello")
End Sub
‘Class module InstrumentType1
Function SendString(OutBuffer As String) As String
OutBuffer = "AAA" & OutBuffer
Worksheets("Sheet1").Range("A10").Value = OutBuffer
End Function
‘Class module InstrumentType2
Function SendString(OutBuffer As String) As String
OutBuffer = "BBB" & OutBuffer
Worksheets("Sheet1").Range("A10").Value = OutBuffer
End Function
My thought was that I could create a class for each model. In the beginning of the code, I want to declare an object to one of these classes. I want to do this to avoid having my code full of “if” and “case”.
I have written this simple sample code and it seem to work without declaration of the object. If I add a declaration, I get error message “Type Mismatch” or “Duplicate declaration in current scope” deepening on where I put the declaration. Is there any downside running the code without declaration or is it any alternative method I can use doing the same thing?
'Dim Inst As InstrumentType1
Sub Test()
Dim i As Integer
i = Worksheets("Sheet1").Range("A1").Value
If i = 1 Then
'Dim Inst As InstrumentType1
Set Inst = New InstrumentType1
Else
'Dim Inst As InstrumentType2
Set Inst = New InstrumentType2
End If
Receive = Inst.SendString("Hello")
End Sub
‘Class module InstrumentType1
Function SendString(OutBuffer As String) As String
OutBuffer = "AAA" & OutBuffer
Worksheets("Sheet1").Range("A10").Value = OutBuffer
End Function
‘Class module InstrumentType2
Function SendString(OutBuffer As String) As String
OutBuffer = "BBB" & OutBuffer
Worksheets("Sheet1").Range("A10").Value = OutBuffer
End Function