奇怪的行为:不使用Set而是将Variant Set设置为Object

Tin*_*Man 11 vba

在将我的分析器从ProcessID写入VBA创建IE对象时,我遇到了这种奇怪的行为。请注意,即使win未将变量设置为IWebBrowser对象,也仍然Set是该IWebBrowser对象。

我想念什么吗???请问Matt,Continium,ThunderFrames ...有人喜欢Set me Straight吗?

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

立即窗口截图

Tin*_*Man 5

我可以通过让类返回接口作为其默认成员来复制行为。感谢John Coleman和Tim Williams给我这个主意。接口: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
Run Code Online (Sandbox Code Playgroud)

类别: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
Run Code Online (Sandbox Code Playgroud)

测试

Sub Test()
    Dim win As Variant
    Dim MyClass2 As New Class2
    win = MyClass2
    Debug.Print IsObject(win), TypeName(win)
End Sub
Run Code Online (Sandbox Code Playgroud)

结果

立即窗口屏幕截图