[英]Excel VBA: Why am I getting a run-time error 438 when adding custom class object into custom class array?
I get that there are a few other posts about this error on here and other places, but the things causing the issue seem to be all over the place and none of the solutions I've seen so far seem to fix the issue I'm facing.我知道这里和其他地方还有一些关于此错误的其他帖子,但导致问题的原因似乎无处不在,到目前为止我所看到的解决方案似乎都没有解决我遇到的问题面对。
I have a class module with the following code:我有一个 class 模块,代码如下:
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
When I run this code, I get the run-time error 438, but I don't understand why.当我运行这段代码时,我得到了运行时错误 438,但我不明白为什么。 The array is looking for the
Line
object.该阵列正在寻找
Line
object。 The Line
object I am trying to put in is not null.我试图放入的
Line
object 不是 null。
When I pause on the line giving me issue:当我暂停在线给我的问题时:
Set lines(u) = ln
From: https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2003/aa192490(v=office.11)?redirectedfrom=MSDN来自: https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2003/aa192490(v=office.11)?redirectedfrom=MSDN
"In VBA, the Set keyword is necessary to distinguish between assignment of an object and assignment of the default property of the object." “在 VBA 中,必须使用 Set 关键字来区分 object 的分配和 object 的默认属性的分配。”
Because this works fine in VBA:因为这在 VBA 中工作正常:
Dim a
a = Range("a1") 'implicitly uses default property: Range("A1").Value
...when you want to get a reference in a
to the actual Range object (and not its value) then you need to use Set to tell the runtime what you really want: ...当您想
a
对实际 Range object (而不是其值)的引用时,您需要使用 Set 来告诉运行时您真正想要什么:
Set a = Range("a1")
So the need to use Set
is a side-effect of the "convenience" of having default properties such as Value
因此,需要使用
Set
是具有默认属性(例如Value
)的“便利”的副作用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.