Vba 奇怪的行为:变量集为对象而不使用集合
当我写我的答案时,我偶然发现了这种奇怪的行为。请注意,即使Vba 奇怪的行为:变量集为对象而不使用集合,vba,Vba,当我写我的答案时,我偶然发现了这种奇怪的行为。请注意,即使win变量未设置为IWebBrowser对象,它仍然是set设置为IWebBrowser对象 我错过什么了吗???Matt、Continium、ThunderFrames……请告诉我这件事好吗 Sub WierdBehavior() Dim win As Variant win = CreateObject("Shell.Application").Windows Debug.Print IsObject(win)
win
变量未设置为IWebBrowser
对象,它仍然是set
设置为IWebBrowser
对象
我错过什么了吗???Matt、Continium、ThunderFrames……请告诉我这件事好吗
Sub WierdBehavior()
Dim win As Variant
win = CreateObject("Shell.Application").Windows
Debug.Print IsObject(win), TypeName(win)
End Sub
我能够通过让一个类返回一个接口作为其默认成员来复制behavoir。感谢约翰·科尔曼和蒂姆·威廉姆斯给了我这个想法。 接口: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
类别:类别2
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
试验
结果
有趣,但无论如何都不太可能有多大意义。变体是引擎盖下的指针。此特定对象的某些特性允许将其分配给
win
,而不使用关键字set
。也许这个对象以某种方式将自己作为默认属性?可能更多地与将win分配给shell对象的属性有关-对于后期绑定代码,无法知道将是什么类型的对象,因此编译器不会标记它?编辑:如果您删除.Windows
,则需要设置如果您在赋值之前插入Set
,则win
的类型将变为IShellWindows
,而不是IWebBrowser2
,因此后者必须是前者的默认属性。每当您为对象变量赋值引用时,分配使用Set关键字。如果不使用Set,Visual Basic将尝试查找对象变量的默认属性并设置该默认属性。
@TinMan可能再等一天左右。如果赋值的右侧是一个对象,而左侧不使用Set
,则赋值默认为对象的默认属性(如果有)的赋值是相当标准的。您始终可以在范围对象中看到它(其中默认属性为Value
)。您的问题的新之处在于,默认值本身可以是一个对象,这是我不知道的。我们可能已经给了你这个想法,但你已经实现了。
Sub Test()
Dim win As Variant
Dim MyClass2 As New Class2
win = MyClass2
Debug.Print IsObject(win), TypeName(win)
End Sub