VB6运行时类型检索

6

在VB6中,如何在运行时获取对象的类型(仅字符串名称即可)?

例如:

If Typeof(foobar) = "CommandButton" Then ...

/编辑:为了澄清,我需要检查动态类型对象。例如:

Dim y As Object 

Set y = CreateObject("SomeType")

Debug.Print( <The type name of> y)

输出结果应为“CommandButton”。
4个回答

8
我认为你需要的是 TypeName 而不是 TypeOf。
If TypeName(foobar) = "CommandButton" Then
   DoSomething
End If

编辑:你所说的动态对象是什么意思?你是指使用CreateObject("")创建的对象吗?因为那应该仍然有效。
Private Sub Command1_Click()
    Dim oObject As Object
    Set oObject = CreateObject("Scripting.FileSystemObject")
    Debug.Print "Object Type: " & TypeName(oObject)
End Sub

输出

对象类型:FileSystemObject


也许我应该澄清一下我的问题,我想知道动态类型对象是什么,因此在我的情况下使用TypeName只会返回“Object”。 - DAC

3

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

2
我没有VB6的副本,但我认为你需要
Typename()

函数...

我在Excel VBA中看到了它,所以它可能在同一个运行时中。有趣的是,帮助似乎暗示它不应该对用户定义类型起作用,但那是我使用它的唯一方式。

来自帮助文件的摘录:

TypeName 函数

返回提供有关变量信息的字符串。

语法

TypeName(varname)

必需的varname参数是一个变体,其中包含任何变量,除了用户定义类型的变量。


0
这可能会很困难,因为在VB6中,所有对象都是COM(IDispatch)对象。因此它们只是一个接口。 TypeOf(object) is class 可能只是进行了一次COM get_interface调用(我忘记了确切的方法名称,抱歉)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接