DefType Statements in VBA

Posted: June 6, 2013 by Transformer in VBA
Tags:

The syntax for declaring a variable in VBA is:

       Dim [VariableName]     As [VariableType]

If the variable type is not specified, then the variable becomes a Variant by default. However, this behavior can be modified using DefType statements. A DefType statement can be used to set the default data type for those Variables/Functions(return type)/Function-Parameters whose names start with the specific characters. However it does not affect those variables that are explicitly declared using a Dim…As statement.

Syntax :   DefType letter  OR   DefType letter1,letter2…… OR  DefType letter1 – letter2

DefType could only be used in one of the following ways for each of the data types:
DefBool , DefByte , DefInt , DefLng , DefCur , DefSng , DefDbl , DefDec , DefDate , DefStr , DefObj , DefVar .

Example:
In the following program, DefStr  S  sets the data type of variable sName as String, since its data type is not explicitly specified and its name starts with ‘S’. However, it does not change the data type of sAge variable because its data type is explicitly specified as Long.

Option Explicit
DefStr S

Sub Deftype_Example()

    Dim sName
    Dim sAge      As Long

    Debug.Print TypeName(sName)     ' Prints String
    Debug.Print TypeName(sAge)      ' Prints Long

End Sub

In the following program data type of parameter  sName  and return type of  function SFunction is not specified. So those will be set as String because of the DefType statement.

Option Explicit
DefStr S

Function SFunction(sName)

    Debug.Print TypeName(sName) 'Print String

End Function

Sub Caller()

    Debug.Print TypeName(SFunction("UsefulGyaan")) 'Prints String

End Sub

Similarly a range of letters can also be passed in place of S.
e.g.
DefStr A-Z
DefStr A,B,D

Note: DefType statement works only at a module-level.

Advertisements

Share your thoughts/feedback

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s