【发布时间】:2020-05-04 17:17:19
【问题描述】:
我知道这里和其他地方还有一些关于此错误的其他帖子,但导致问题的原因似乎无处不在,到目前为止我看到的解决方案似乎都没有解决问题我正在面对。
我有一个类模块,代码如下:
Public questionID As Integer
Public score As Double
Public time As Date
Private lines() As New Line 'If I remove 'New', I end up getting Run-time error 91 instead
Sub CreateByRow(row As Range)
questionID = row.Cells(1, 1)
score = row.Cells(1, 7)
time = row.Cells(1, 8)
''' INSERT LINES '''
Dim tLines As ListObject
Set tLines = shtLines.ListObjects("lines")
Erase lines
Dim rLine As Range
For Each rLine In tLines.Range.Rows
If rLine.Cells(1, 1) = questionID Then
Dim ln As New Line
ln.CreateByRow rLine 'Line object is created as expected
u = UBound(lines) + 1 'u = 0 as expected
ReDim lines(u) 'Array has a length of 1 and index of 0 as expected
lines(u) = ln 'This is where the error happens
End If
Next
End Sub
当我运行这段代码时,我得到了运行时错误 438,但我不明白为什么。该数组正在寻找Line 对象。我试图放入的Line 对象不为空。
当我在给我问题的行上暂停时:
【问题讨论】:
-
Set lines(u) = ln此外,ReDim lines(u)将删除您数组中的任何现有内容 - 您需要使用ReDim Preserve来避免这种情况。 -
你知道的。现在我很生气,解决方案如此简单。我希望有更大的东西。我真的不明白
Set的关键字是什么,什么时候应该使用它。感谢您的帮助。 -
是的,我意识到我第一次运行时忘记添加
Preserve。 -
"在 VBA 中,必须使用 Set 关键字来区分对象的赋值和对象的默认属性的赋值。" docs.microsoft.com/en-us/previous-versions/office/developer/… 可能还有 stackoverflow.com/questions/9481140/…
-
当然,对于一维数组,如果您使用 Collection 或 Dictionary 代替数组,那么所有 redim 保留恶作剧的痛苦都会被消除。
标签: arrays excel vba runtime-error