代码之家  ›  专栏  ›  技术社区  ›  rory.ap

将变量数组传递给方法会产生“类型不匹配”错误

vba
  •  6
  • rory.ap  · 技术社区  · 11 年前

    我有以下两种方法:

    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
    

    我的项目引用了“Microsoft Scripting Runtime”来提供 Dictionary 上面使用的类。尽管事实上 x.Items 返回一个 Variant() (如 MsgBox TypeName(x.Items) ,我在上遇到以下编译错误 Call Test(x.Items) :

    类型不匹配:应为数组或用户定义的类型

    怎么了?

    注意:如果我更改 Test 方法:

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

    它成功并显示 变量() 。为什么我不能将参数明确声明为 变量() 类型

    1 回复  |  直到 11 年前
        1
  •  8
  •   The other other Alan    11 年前

    Items 是一个 Variant 未声明的类型,这意味着就编译器而言,它在运行时可以是任何东西,不一定是数组。当然,我们知道它将是一个数组,因为它是字典的一部分,但它没有声明的类型(对象浏览器显示它是一个没有返回类型的函数),因此它默认为Variant。由于编译器不能保证它在运行时是一个数组,所以它不允许您在Test()过程中尝试的声明。 在运行时,它变成一个数组,因此 TypeName() 显示为 Variant()

    有趣的是,VBA确实允许向变量数组赋值,因此这是有效的:

    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