VB6运行时类型检索
时间:2020-03-05 18:50:08 来源:igfitidea点击:
在运行时如何在VB6中获取对象的类型(名称作为字符串就足够了)?
即类似:
If Typeof(foobar) = "CommandButton" Then ...
/编辑:为了澄清,我需要检查动态类型的对象。一个例子:
Dim y As Object Set y = CreateObject("SomeType") Debug.Print( <The type name of> y)
输出将是" CommandButton"
解决方案
回答
事实证明这很困难,因为在VB6中所有对象都是COM(IDispatch)对象。因此,它们只是一个接口。
" TypeOf(object)is class"可能只执行COM get_interface调用(抱歉,我忘记了确切的方法名称)。
回答
我认为我们正在寻找的是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
回答
我没有VB6的副本,但我认为我们需要
Typename()
函数...我可以在Excel VBA中看到它,因此它可能在同一运行时中。有趣的是,该帮助似乎表明它不适用于用户定义的类型,但这是我使用它的唯一方法。
摘录自帮助文件:
TypeName Function Returns a String that provides information about a variable. Syntax TypeName(varname) The required varname argument is a Variant containing any variable except a variable of a user-defined type.
回答
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