我的VBA代码中有一些用户定义的对象,并且想知道是否有办法检查对象类型是什么。有点像
Dim myObject as Variant
Set myObject= New Employee
If(myObject isType Employee)
Do Something
Else
Do something else
我在考虑VarType()函数,但它显然不适用于用户定义的类型。还有其他我可以使用的东西吗?
答案 0 :(得分:2)
有两种可能性。以下代码应该解释一切。请参阅内部的其他评论:
Sub qTest()
Dim myObject As Variant
Set myObject = New Employee
'return results to Immediate
Debug.Print TypeName(myObject) '>> will return class name
Debug.Print TypeOf myObject Is Employee '>>will return true
'using with 'if statements', both will return true
If TypeName(myObject) = "Employee" Then
MsgBox "OK"
End If
If TypeOf myObject Is Employee Then
MsgBox "OK"
End If
End Sub
答案 1 :(得分:1)
我相信你正在寻找TypeOf
。使用上面的示例,可以按如下方式使用:
Dim myObject as Variant
Set myObject= New Employee
If TypeOf myObject is Employee Then
Do Something
Else
Do SomethingElse
End If