Excel VBA:将对象添加到类

时间:2015-04-27 09:55:49

标签: excel vba class collections

我正在尝试创建一个包含集合(名为DefectCollection)的类(名为ClassSection)。它需要一个函数来添加项目到该集合,但我无法使其工作。我得到错误91“对象变量或未设置块变量。”

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

这是类模块代码:

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'是另一个类,工作正常 - 我希望每个'ClassSection'能够容纳无限数量的'缺陷')

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

谢谢!

1 个答案:

答案 0 :(得分:0)

您收到错误,因为DefectCollectionNothing。这是因为您错误地使用了初始化方法:

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

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