数组中的工作表对象自动清除?

时间:2013-10-03 14:54:42

标签: arrays excel vba excel-vba

好吧,我遇到了一个奇怪的错误,我不确定它为什么会发生。让我分解一下这个程序的工作原理。所以对于这个程序,我填充了一个充满不同东西的数组。第一个元素Array_WS(0)是工作表对象,下一个,Array_WS(1)是工作表的标题行号等。当我将Array_WS传递给另一个过程时,一切都很好。但是,当我输入With语句时,With Array_WS(0)清除元素...是的,你听到了正确的答案。当我逐步完成代码时,恰好在分配With Array_WS(0) Sheet1之前......然后在输入With语句后立即bam,Array_WS(0)为空。以下示例应该使这更清楚。

这是代码的外观:

问题

Sub WTF(Array_WS as Variant)
Dim greatValue%

With Array_WS(0)
   greatValue = .Cells(1,1).Value2 <= this works even though Array_WS(0) is now empty
End With

greatValue = Array_WS(0).Cells(1,1).Value2 <= outside the With statement throws an exception

修复

我想出的解决方法就是这个

Sub WTF(Array_WS as Variant)
Dim greatValue%, WS as Worksheet

Set WS = Array_WS(0)

With WS
   greatValue = .Cells(1,1).Value2 <= this works
End With

greatValue = Array_WS(0).Cells(1,1).Value2 <= this also works

问题

虽然我发现了一种解决方法,但我只是想知道,为什么会发生这种情况?。我是否遗漏了一些关于数组中的对象如何被传递的工作?或者也许是否有一些我没有得到的With语句?

非常感谢任何帮助!

感谢, 贾斯汀

1 个答案:

答案 0 :(得分:1)

即使将单个对象作为Variant数组传递也会产生问题。以下将死于第三个MsgBox:

Sub MAIN()
    Dim ary(1 To 1) As Variant
    Set ary(1) = ActiveSheet
    Call routine(ary)
End Sub

Sub routine(v As Variant)
    MsgBox v(1).Name
    With v(1)
        MsgBox .Name
    End With
    MsgBox v(1).Name
End Sub

但这不会死:

Sub MAIN()
    Dim ary(1 To 1) As Worksheet
    Set ary(1) = ActiveSheet
    Call routine(ary)
End Sub

Sub routine(v As Variant)
    MsgBox v(1).Name
    With v(1)
        MsgBox .Name
    End With
    MsgBox v(1).Name
End Sub