Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange Behavior: Variant Set to Object without using Set

Tags:

vba

While writting my anser to VBA create IE object from ProcessID, I came accross this strange behavior. Notice that even though the win variable isn't set to the IWebBrowser object it is still Set to the IWebBrowser object.

Am I missing something??? Will Matt, Continium, ThunderFrames...someboby please Set me Straight on this?

Sub WierdBehavior()
    Dim win As Variant
    win = CreateObject("Shell.Application").Windows
    Debug.Print IsObject(win), TypeName(win)
End Sub

Immediate Window Screenshot

like image 222
TinMan Avatar asked Aug 02 '19 15:08

TinMan


1 Answers

I was able to replicate the behavoir by having a class return an Interface as its Default Memeber. Credit John Coleman and Tim Williams for giving me the idea. Interface: IClass

VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "IClass"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Public Property Get getFoo() As Object
End Property

Class: Class2

VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "Class2"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Implements IClass
Private MyCollection As New Collection
Private Property Get IClass_getFoo() As Object
    Set Class1_getFoo = MyCollection
End Property

Public Function getInterface() As IClass
Attribute getInterface.VB_UserMemId = 0
    Set getInterface = Me
End Function

Test

Sub Test()
    Dim win As Variant
    Dim MyClass2 As New Class2
    win = MyClass2
    Debug.Print IsObject(win), TypeName(win)
End Sub

Results

Immediate Window Screen Shot

like image 190
TinMan Avatar answered Oct 31 '22 14:10

TinMan