2008-09-09 61 views
6

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

即是这样的:

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

/编辑:澄清,我需要检查动态类型的对象。举个例子:

Dim y As Object 

Set y = CreateObject("SomeType") 

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

对输出将是 “命令按钮”

回答

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 

输出

Object Type: FileSystemObject

+0

也许我要澄清我的问题,我想知道一个动态类型的对象是什么,使用这样的TypeName会(在我的情况下)只返回“对象”。 – DAC 2008-09-09 16:07:50

0

这应该证明是困难的,因为在VB6中的所有对象都是COM(IDispatch)的东西。因此他们只是一个界面。

TypeOf(object) is class可能只是一个COM get_interface调用(我忘了确切的方法名称,对不起)。

2

我没有VB6的副本的手,但我认为你需要的

​​

功能。 ..我可以在Excel VBA中看到它,所以它可能在同一个运行时。有趣的是,该帮助似乎表明它不应该为用户定义的类型工作,但这是我使用它的唯一方法做了。从帮助文件

摘录:

TypeName函数

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

语法

类型名(VARNAME)

所需VARNAME参数是包含任何变量除了 用户定义类型的一个可变变 。

2

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