Thank you for your support!    
UtterAccess HomeUtterAccess Wiki

Welcome Guest ( Log In | Register )

Edit Discussion
> TypeOf    

TypeOf

The TypeOf statement can be used to check if an object reference is a specified type of object. For example, we can use TypeOf to see if a Control is a Textbox, or a Form, or a Class Object.

In VBA, the Help for TypeOf can be found under the If/Then help file, and is sparing in it's description.


Contents

Basic Syntax

The basic syntax is as follows:

If TypeOf MyObject Is ObjectType Then

Substitute MyObject with your object reference, and ObjectType with the type of object you would like to test for. For example:

If TypeOf Me.ControlName Is Access.TextBox Then Msgbox Me.ControlName & " is a TextBox"

The "TypeOf X Is Y" clause can be used in many cases where a boolean variable can be returned. For Example:

While TypeOf ctl.Parent Is Access.Form = False
MsgBox Iif(TypeOf ctl.Parent Is Access.Form, "Is Form", "Is Not Form")

You can negate the return through one of the following two syntaxes:

If Not TypeOf ObjectReference Is ObjectType
If TypeOf ObjectReference Is ObjectType = False


Derived Objects and TypeOf

TypeOf can be used to compare objects to a derived object. For example, a Textbox control might be checked against an Access.TextBox, an Access.Control and an Object, all of which return True:

Debug.Print Iif(TypeOf Me.txtName Is Access.TextBox, True, False)
Debug.Print Iif(TypeOf Me.txtName Is Access.Control, True, False)
Debug.Print Iif(TypeOf Me.txtName Is Object, True, False)
Debug.Print Iif(TypeOf Me.txtName Is Access.Form, True, False)

This would yield the following results:

True
True
True
False


Custom (Class) Objects

TypeOf can be used on any object. For example, if we have a class clsMyClass, and we want to see if an object is an instance of MyClass, we can use the following:

If TypeOf MyObject Is clsMyClass Then MsgBox "It's of the MyClass type"

Restrictions

TypeOf cannot be used to determine if a variable is a user defined type, nor can it be used to see if a variable is of a standard type (Integer, String, Boolean, etc).

Edit Discussion
This page was last modified 17:04, 11 February 2012.  This page has been accessed 289 times.  Disclaimers