在VB6中,如何在运行时获取对象的类型(仅字符串名称即可)?
例如:
If Typeof(foobar) = "CommandButton" Then ...
/编辑:为了澄清,我需要检查动态类型对象。例如:
Dim y As Object
Set y = CreateObject("SomeType")
Debug.Print( <The type name of> y)
输出结果应为“CommandButton”。
If TypeName(foobar) = "CommandButton" Then
DoSomething
End If
Private Sub Command1_Click()
Dim oObject As Object
Set oObject = CreateObject("Scripting.FileSystemObject")
Debug.Print "Object Type: " & TypeName(oObject)
End Sub
输出
对象类型:FileSystemObject
TypeName是你想要的...这里有一些示例输出:
VB6代码:
Private Sub cmdCommand1_Click()
Dim a As Variant
Dim b As Variant
Dim c As Object
Dim d As Object
Dim e As Boolean
a = ""
b = 3
Set c = Me.cmdCommand1
Set d = CreateObject("Project1.Class1")
e = False
Debug.Print TypeName(a)
Debug.Print TypeName(b)
Debug.Print TypeName(c)
Debug.Print TypeName(d)
Debug.Print TypeName(e)
End Sub
结果:
String
Integer
CommandButton
Class1
Boolean
Typename()
函数...
我在Excel VBA中看到了它,所以它可能在同一个运行时中。有趣的是,帮助似乎暗示它不应该对用户定义类型起作用,但那是我使用它的唯一方式。
来自帮助文件的摘录:
TypeName 函数
返回提供有关变量信息的字符串。
语法
TypeName(varname)
必需的varname参数是一个变体,其中包含任何变量,除了用户定义类型的变量。
TypeOf(object) is class
可能只是进行了一次COM get_interface调用(我忘记了确切的方法名称,抱歉)。