tags:

views:

790

answers:

4

How can you obtain the Type (the name as a string is sufficient) of an Object in VB6 at runtime?

i.e. something like:

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

/EDIT: to clarify, I need to check on Dynamically Typed objects. An example:

Dim y As Object 

Set y = CreateObject("SomeType")

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

Where the output would be "CommandButton"

A: 

This should prove difficult, since in VB6 all objects are COM (IDispatch) things. Thus they are only an interface.

TypeOf(object) is class probably only does a COM get_interface call (I forgot the exact method name, sorry).

Daren Thomas
+5  A: 

I think what you are looking for is TypeName rather than TypeOf.

If TypeName(foobar) = "CommandButton" Then
   DoSomething
End If

Edit: What do you mean Dynamic Objects? Do you mean objects created with CreateObject(""), cause that should still work.

Edit:

Private Sub Command1_Click()
    Dim oObject As Object
    Set oObject = CreateObject("Scripting.FileSystemObject")
    Debug.Print "Object Type: " & TypeName(oObject)
End Sub

Outputs

Object Type: FileSystemObject

Kris Erickson
Maybe I should clarify my question, I want to know what a dynamically typed Object is, so using TypeName will (in my case) only return "Object".
DAC
+1  A: 

I don't have a copy of VB6 to hand, but I think you need the

Typename()

function... I can see it in Excel VBA, so it's probably in the same runtime. Interestingly, the help seems to suggest that it shouldn't work for a user-defined type, but that's about the only way I ever do use it.

Excerpt from the help file:

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.

Mike Woodhouse
+1  A: 

TypeName is what you want... Here is some example output:

VB6 Code:

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

Results:

String
Integer
CommandButton
Class1
Boolean
sharvell