Search notes:

VBA: function typeOf … is

The typeOf var is classname construct allows to check if a given variable is of a particular type.

Two classes

First, we define two (simple) classes:
public memberVar as string
Github repository about-VBA, path: /functions/typeOf-is/classOne.cls
public m_var as double
Github repository about-VBA, path: /functions/typeOf-is/classTwo.cls

Using typeOf

Now, we're ready to use typeOf … is on instances (objects) of these classes:
option explicit

sub determineType(obj as variant)

    if obj is nothing then
       debug.print "nothing"

     ' If the object is »nothing«, it makes no sense to continue
     ' with typeOf … is checks: nothing-objects cause error message:
     '   Object variable or With block variable not set.
     '
     ' Thus, we exit the sub:
       exit sub
    end if

    if typeOf obj is object then
       debug.print "object"
    end if

    if typeOf obj is classOne then
       debug.print "classOne"
    end if

    if typeOf obj is classTwo then
       debug.print "classTwo"
    end if

end sub

sub main()

    dim obj_1 as     classOne
    dim obj_2 as new classTwo

    determineType obj_1
    determineType obj_2

end sub
Github repository about-VBA, path: /functions/typeOf-is/main.bas

Interna

It can be strongly assumed that typeOf() calls QueryInterface() to determine if var is of the given type.

See also

typeName()
VBA functions
The JavaScript operator typeof

Index