Determine Variable Data Type VBA (Visual Basic for Applications) example

Determine Variable Data Type VBA (Visual Basic for Applications) example

TypeName

A generic object which takes an input and returns its Data type in String format.

Code example

Function GetDataType(variable As Variant)
    GetDataType = TypeName(variable)
End Function

Calling Method

Sub DetermineDataTypes()
    a = 1
    b = "te"
    c = 12.5
    
    Debug.Print "I am a " & GetDataType(a) & " Type Variable"
    Debug.Print "I am a " & GetDataType(b) & " Type Variable"
    Debug.Print "I am a " & GetDataType(c) & " Type Variable"
End Sub

Output

I am a Integer Type Variable
I am a String Type Variable
I am a Double Type Variable

TypeOf … Is

The TypeName function returns a string and is the best choice when you need to store or display the class name of an object:

Sub DetermineDataTypes()
    Dim oChart As Chart
    Set oChart = ActiveChart
    
    'test chart object
    If TypeOf oChart Is Chart Then
        MsgBox "This is a Chart Object"
    End If
    
    'Memory cleanup
    Set oChart = Nothing
End Sub

Output

Leave a Reply

Your email address will not be published.