Passing an array variant to a method causes a "Mismatch Type" error

I have the following two methods:

Sub Start() Dim x As Dictionary Set x = New Dictionary Call x.Add("first", 1) MsgBox TypeName(x.Items) 'Displays "Variant()" Call Test(x.Items) End Sub Sub Test(withArray() As Variant) End Sub 

My project references the "Microsoft Scripting Runtime" to provide the Dictionary class used above. Despite the fact that x.Items returns a Variant() (as shown by MsgBox TypeName(x.Items) , I get the following compilation error on Call Test(x.Items) :

Type mismatch: an array or user-defined type is expected

What's wrong?

Note: if I changed the Test method to:

 Sub Test(withArray) MsgBox TypeName(withArray) End Sub 

It succeeds and displays Variant() . Why can't I explicitly declare an argument as a type of Variant() ?

+5
source share
1 answer

Items is a Variant undeclared type, which means that with respect to the compiler, it can be anything at all at runtime - not necessarily an array. Of course, we know that it will be an array, because it is part of the dictionary, but it does not have a declared type (Object Browser shows that it is a function without a return type), so Variant is used by default. Since the compiler cannot guarantee that it will be an array at runtime, it does not allow the declaration that you are trying to execute in the Test () test. At runtime, it becomes an array, so TypeName() shows it as Variant()

Interestingly, VBA allows you to assign a variant array, so this works:

 Sub Start() Dim x As Dictionary Dim y() As Variant Set x = New Dictionary Call x.Add("first", 1) MsgBox TypeName(x.Items) 'Displays "Variant()" y = x.Items ' this is fine Call Test(y) 'this works End Sub Sub Test(withArray() As Variant) End Sub 
+8
source

Source: https://habr.com/ru/post/1201737/


All Articles