Excel VBA: 将对象添加到 class 中的集合

Excel VBA: Adding objects to a collection within a class

我正在尝试创建一个 class(名为 ClassSection),其中包含一个集合(名为 DefectCollection)。它需要一个将项目添加到该集合的功能,但我无法使其正常工作。我收到错误 91 "Object variable or with block variable not set."

我已经看过这里的其他答案,这是我走到这一步的原因,但我不明白我错过了什么。

这里是 class 模块代码:

Public DefectCollection As Collection

Private Sub Class_Initialise()
    Set DefectCollection = New Collection
End Sub

Public Function AddDefect(ByRef defect As CDefect)
    DefectCollection.Add defect [<---- error 91]
End Function

这里是调用该函数的代码:('defect' 是另一个 class,它工作正常 - 我希望每个 'ClassSection' 能够容纳无限数量的'defects')

Dim SC As Collection
Dim section As ClassSection
Set SC = New Collection

Dim SurveyLength As Double

For Each defect In DC
    SurveyLength = WorksheetFunction.Max(SurveyLength, defect.Pos, defect.EndPos)
Next defect

SurveyLength = Int(SurveyLength)

For i = 0 To numSurveys
    For j = 0 To SurveyLength
        Set section = New ClassSection
        section.ID = CStr(j & "-" & dates(i))
        SC.Add Item:=section, Key:=section.ID
    Next j
Next i


Dim meterage As Double

For Each defect In DC
    meterage = Int(defect.Pos)
    Set section = SC.Item(meterage & "-" & defect.SurveyDate)
    section.AddDefect defect
Next defect

谢谢!

你得到这个错误是因为 DefectCollectionNothing。这是因为您将初始化方法拼错了:

Private Sub Class_Initialise() '<-- it's with "Z", not "S"

因此,永远不会调用 class 的初始化,默认情况下对象保持 Nothing 并且尝试将对象添加到 Nothing[=15= 时该方法失败]