调用另一个子时出现类型不匹配错误

时间:2018-10-01 12:29:08

标签: vba

以下代码为我提供了类型不匹配错误。我已经通过内部变体数组测试了HideTabs,它确实有效。有人可以帮忙吗?

Public Sub MainSub()
    Dim tab_names As Variant
    tab_names = Array("Sheet2", "Sheet3")
    Call HideTabs(tab_names)
End Sub

Public Sub HideTabs(ws_names() As Variant)
    Dim ws_name As Variant
    For Each ws_name In ws_names()
        ThisWorkbook.Worksheets(ws_name).Visible = False
    Next ws_name
End Sub

2 个答案:

答案 0 :(得分:2)

您可以编写如下。您不需要将()作为变体ByVal传递给子对象。

Public Sub MainSub()
    Dim tab_names As Variant
    tab_names = Array("Sheet2", "Sheet3")
    HideTabs tab_names
End Sub

Public Sub HideTabs(ByVal ws_names As Variant)
    Dim ws_name As Variant
    For Each ws_name In ws_names
        ThisWorkbook.Worksheets(ws_name).Visible = False
    Next ws_name
End Sub

enter image description here

答案 1 :(得分:2)

MainSub中定义tab_names As Variant,而HideTabs的参数应为ws_names() as Variant

一个是Variant,可以存储(在所有其他简单类型和对象之间)一个数组,而另一个是Variant Array,可以存储Variants(每个都可以依次存储一个数组。)

实际上,您正在尝试将标量作为参数传递给期望数组的位置。

要修复代码,请确保两个声明都使用相同的类型(Variant Array,因为“标量” Variant中的隐式数组似乎无法与For Each一起使用)

Public Sub MainSub()
    Dim tab_names() As Variant
    tab_names = Array("Sheet2", "Sheet3")
    HideTabs tab_names ' "Call" is obsolete. Don't use it.
End Sub

Public Sub HideTabs(ByVal ws_names() As Variant)
    Dim ws_name As Variant
    For Each ws_name In ws_names()
        ThisWorkbook.Worksheets(ws_name).Visible = False
    Next ws_name
End Sub

QHarr's answer所示,不需要括号-没有括号就可以使用。但是,如果您直接需要一个数组,则无需检查Variant参数是否包含数组。