简体   繁体   English

在 Visual Basic 中将数组作为参数传递会导致 Excel 崩溃

[英]Passing an array as argument in Visual Basic causes Excel to crash

Here's the minimum amount of code that produces the problem.这是产生问题的最少代码量。 I have a module and two classes ("Test" and "Test2").我有一个模块和两个类(“Test”和“Test2”)。 In Module1, I have this function:在 Module1 中,我有这个 function:

Sub testf()
    Dim s() As String
    ReDim s(0) As String
    s(0) = "value"
    Dim t As New Test
    t.first = s
End Sub

in the class Test, I have this:在 class 测试中,我有这个:

Property Let first(s() As String)
    Debug.Print "first"
    Dim t As New Test2
    t.second = s
End Property

and finally in the class Test2, I have:最后在 class Test2 中,我有:

Property Let second(s() As String)
    Debug.Print "second"
End Property

Running the Sub testf will cause Excel to close and reopen.运行 Sub testf将导致 Excel 关闭并重新打开。 I don't get a popup telling me that there's a run-time error, so I don't know what the error is.我没有弹出窗口告诉我存在运行时错误,所以我不知道错误是什么。 It reaches first and, so, the issue is with how second is being called.first到达,因此问题在于如何调用second Attempting to do error handling within first doesn't help.尝试first进行错误处理并没有帮助。 For example, placing an "on error..." preceding t.second = s to get the error description doesn't work.例如,在t.second = s之前放置一个“on error...”来获取错误描述是行不通的。

If we change second to accept a variant argument instead, then this solves the problem and there is no crash.如果我们将second更改为接受一个变体参数,那么这就解决了问题并且没有崩溃。 But that doesn't help me understand what the issue was to begin with.但这并不能帮助我理解问题的根源。 Printing the variable type of s before t.second = s confirms that it's 8200, which is a string array.t.second = s s之前打印 s 的变量类型确认它是 8200,它是一个字符串数组。 So then what's the problem with how second accepts its argument?那么second如何接受它的论点有什么问题呢?

The provided code produced a RTE 51: Internal Error for me.提供的代码为我生成了 RTE 51:内部错误。 The setup seems odd to me, but the following works:设置对我来说似乎很奇怪,但以下工作:

In class Test :在 class Test中:

Private pFirst() As String

Property Let first(s() As String)
    Debug.Print "first"
    pFirst = s
    Dim t As New Test2
    t.second = pFirst
End Property

In class Test2 :Test2测试2:

Private pSecond() As String

Property Let second(s() As String)
    Debug.Print "second"
    pSecond = s
End Property

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM