1

好吧,我遇到了一个奇怪的错误,我不确定它为什么会发生。让我分解一下这个程序是如何工作的。所以对于这个程序,我填充了一个充满不同事物的数组。第一个元素Array_WS(0)是工作表对象,下一个是工作表Array_WS(1)的标题行号等。当我传递Array_WS给另一个程序时,一切都很好。但是,当我输入 With 语句时,With Array_WS(0)会清除元素......是的,你没听错。当我单步执行代码时,就在With Array_WS(0)分配 Sheet1 之前......然后在输入 With 语句时,bamArray_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 语句?

任何帮助将不胜感激!

谢谢,贾斯汀

4

1 回答 1

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
于 2013-10-03T16:08:23.833 回答