VBA TypeOf is followed by a reference type variable or expression which returns an object data type. This object type is compared with another reference type variable using IS keyword. The comparison returns a Boolean value. The negation is obtained using NOT.
The syntax is as follows:
booleanResult = TypeOf expression Is typename
booleanResult = Not TypeOf expression Is typename
Note that TypeOf returns an object data type. where the expression evaluates to a reference data type.
Example 1
Sub TypeOfReferencevariable()
''Early binding
Dim fs As Scripting.FileSystemObject
Set fs = New Scripting.FileSystemObject
'' ref variable type comparison using IS operator
If TypeOf fs Is Scripting.FileSystemObject Then
Debug.Print TypeName(fs)
End If
End Sub
Example 2
Sub TypeOfRefvariable()
''Late binding
Dim fs As Object
Set fs = CreateObject("Scripting.FileSystemObject")
'' ref variable type comparison using IS operator
If TypeOf fs Is Object Then
Debug.Print TypeName(fs)
End If
End Sub
Example 3
The syntax is as follows:
booleanResult = TypeOf expression Is typename
booleanResult = Not TypeOf expression Is typename
Note that TypeOf returns an object data type. where the expression evaluates to a reference data type.
- This operator is mostly used in conjunction with the Is keyword to compare objects.
- This cannot be used with value data types, only reference data types.
- We can use the TypeName function to return the data type as a string.
- We can use the VarType function to return a number indicating the data type.
Example 1
Sub TypeOfReferencevariable()
''Early binding
Dim fs As Scripting.FileSystemObject
Set fs = New Scripting.FileSystemObject
'' ref variable type comparison using IS operator
If TypeOf fs Is Scripting.FileSystemObject Then
Debug.Print TypeName(fs)
End If
End Sub
Example 2
Sub TypeOfRefvariable()
''Late binding
Dim fs As Object
Set fs = CreateObject("Scripting.FileSystemObject")
'' ref variable type comparison using IS operator
If TypeOf fs Is Object Then
Debug.Print TypeName(fs)
End If
End Sub
Example 3
Private Sub UserForm_Initialize()
Dim ctrl As Control
For Each ctrl In Me.Controls
If TypeOf ctrl Is MSForms.TextBox Then
ctrl.Text = vbNullString
End If
Next
End Sub
No comments:
Post a Comment