简体   繁体   中英

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:

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. The array is looking for the Line object. The Line object I am trying to put in is not null.

When I pause on the line giving me issue:

线数据和 Ln 数据的图像

Set lines(u) = ln

From: 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."

Because this works fine in 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:

Set a = Range("a1")

So the need to use Set is a side-effect of the "convenience" of having default properties such as Value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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