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 is referencing "Microsoft Scripting Runtime" to provide the Dictionary
class used above. Despite the fact that x.Items
returns a Variant()
(as demonstrated by MsgBox TypeName(x.Items)
, I'm getting the following compile error on Call Test(x.Items)
:
Type mismatch: array or user-defined type expected
What is wrong?
Note: if I change the Test
method to:
Sub Test(withArray)
MsgBox TypeName(withArray)
End Sub
It succeeds and displays Variant()
. Why can't I explicitly declare the argument as a Variant()
type?
Solution: Try to make assignments only between compatible data types. For example, an Integer can always be assigned to a Long, a Single can always be assigned to a Double, and any type (except a user-defined type) can be assigned to a Variant.
In Excel, on the taskbar, select the File tab, then left-click Open from the list provided. Now click on the required file and select Open -> Open and restore -> Restore (you can also select the Extract data tab). If everything goes well, runtime error 13 will not bother you again.
Type mismatch error, or we can also call it Error code 13, occurs when we assign a value to a variable that is not of its data type. For example, if we provide a decimal or long value to an Integer data type variable, we will encounter this Type mismatch error when we run the code, which shows as error code 13.
A VBA Type Mismatch Error occurs when you try to assign a value between two different variable types. The error appears as “run-time error 13 – Type mismatch”. For example, if you try to place text in a Long integer variable or you try to place text in a Date variable.
Items
is a Variant
of undeclared type, which means as far as the compiler is concerned, it could be anything at all at runtime - not necessarily an array. Of course, WE know it will be an array because its part of a dictionary, but it has no declared type (Object Browser shows it to be a function with no return type) so it defaults to Variant. Since the compiler can't guarantee it will be an array at run-time, it doesn't allow the declaration you are attempting in the Test() proc.
At run-time, it becomes an array, so TypeName()
shows it as Variant()
Interestingly, VBA does allow assignment to 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With