Reputation: 353
I would like to use different data types with same variable and do some computation. For example, I am using the variable "option" in,
If option = 1 then
Do this
Elseif option = "X" then
Do this
Elseif option = 6 then
Do this
Endif
Is there any way i can get this working ?
Upvotes: 1
Views: 1028
Reputation: 1023
You can use a variant to allow for different data types inside of one variable. The below code works.
Public Sub TestVariant()
Dim x As Variant
x = 17
If x = 1 Then
' Do this
ElseIf x = "bob" Then
' Do this
ElseIf x = 17 Then
' This is done
End If
End Sub
Off the top of my head, this smells a bit though. It would be better to have the variable be strictly defined. If you are dealing with numbers that could also be strings, you can always just make the numbers into strings. For example:
Public Sub TestVariant()
Dim x As string
x = "1"
If x = "1" Then
' Do this
ElseIf x = "bob" Then
' Do this
ElseIf x = "17" Then
' This is done
End If
End Sub
Edit: Another example which compiles and works as expected in Excel.
Public Function TestVariant(theOption As Variant)
If theOption < 0 Then
TestVariant = "Negative"
ElseIf theOption = 6 Then
TestVariant = "Six"
ElseIf theOption = "Stuff" Then
TestVariant = "Other Stuff"
Else
TestVariant = theOption
End If
End Function
Upvotes: 2
Reputation: 3750
If you declare option
as Variant
you should be good to go.
Upvotes: 1