如何在运行时获取 VB6 中对象的类型(字符串形式的名称就足够了)?

IE。就像是:

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

/编辑: 为了澄清这一点,我需要检查动态类型对象。一个例子:

Dim y As Object 

Set y = CreateObject("SomeType")

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

输出为“CommandButton”

有帮助吗?

解决方案

我认为您正在寻找的是 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

输出

Object Type: 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

我手头上没有 VB6 的副本,但我认为您需要

Typename()

功能...我可以在 Excel VBA 中看到它,所以它可能在相同的运行时中。有趣的是,帮助似乎表明它不应该适用于用户定义的类型,但这大约是我曾经使用过的唯一方法 用它。

帮助文件摘录:

类型 名称 功能

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

句法

类型名称(变量名称)

所需的varname参数是一个变体,包含任何变量,但用户定义类型的变量除外。

这应该很困难,因为在 VB6 中所有对象都是 COM(IDispatch) 事物。因此它们只是一个接口。

TypeOf(object) is class 可能只进行 COM get_interface 调用(我忘记了确切的方法名称,抱歉)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top