簡體   English   中英

Excel VBA: Why am I getting a run-time error 438 when adding custom class object into custom class array?

[英]Excel VBA: Why am I getting a run-time error 438 when adding custom class object into custom class array?

我知道這里和其他地方還有一些關於此錯誤的其他帖子,但導致問題的原因似乎無處不在,到目前為止我所看到的解決方案似乎都沒有解決我遇到的問題面對。

我有一個 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

當我運行這段代碼時,我得到了運行時錯誤 438,但我不明白為什么。 該陣列正在尋找Line object。 我試圖放入的Line object 不是 null。

當我暫停在線給我的問題時:

線數據和 Ln 數據的圖像

Set lines(u) = ln

來自: https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2003/aa192490(v=office.11)?redirectedfrom=MSDN

“在 VBA 中,必須使用 Set 關鍵字來區分 object 的分配和 object 的默認屬性的分配。”

因為這在 VBA 中工作正常:

Dim a
a = Range("a1")   'implicitly uses default property: Range("A1").Value

...當您想a對實際 Range object (而不是其值)的引用時,您需要使用 Set 來告訴運行時您真正想要什么:

Set a = Range("a1")

因此,需要使用Set是具有默認屬性(例如Value )的“便利”的副作用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM