2

我搜索了一下,但找不到足够相似的问题/答案。所以这里是:

我有一个名为 Project 的类对象。一个项目可以有多个与之相关的场景。

我为每个对象创建了类模块。但我相信,我在为给定项目实例化场景集合时遇到了困难。

以下是类模块:

1) 项目:

Private pProjectID As Integer 
Private pName As String 
Private pDateCreated As String 
Private pScenarios As cScenarios

' PROPERTIES

Public Property Get ProjectID() As Integer
    ProjectID = pProjectID 
End Property
Public Property Let ProjectID(value As Integer)
    pProjectID = value 
End Property
Public Property Get name() As String
    name = pName 
End Property 
Public Property Let name(value As String)
    pName = value 
End Property 
Public Property Get Scenarios() As cScenarios
    Set Scenarios = pScenarios 
End Property
Public Property Set Scenarios(value As cScenarios)
    Set pScenarios = value 
End Property

2)cScenarios集合类模块:

Private pScenarios As Collection

Private Sub Class_Initialize()
    Set pScenarios = New Collection
End Sub
Private Sub Class_Terminate()
    Set pScenarios = Nothing
End Sub
Public Function Item(index As Variant) As cScenario
    Set Item = pScenarios.Item(index)
End Function
Public Property Get Count() As Long
    Count = pScenarios.Count
End Property
Public Sub Add(obj As cScenario)
    pScenarios.Add obj
End Sub
Public Sub Remove(index As Variant)
    pScenarios.Remove index
End Sub

最后(3)场景类对象:

Private pScenarioID As Integer
Private pName As String
Private pDateCreated As String
Private pParent As cProject

Public Property Get ScenarioID() As Integer
    ScenarioID = pScenarioID
End Property
Public Property Let ScenarioID(value As Integer)
    pScenarioID = value
End Property
Public Property Get name() As String
    name = pName
End Property
Public Property Let name(value As String)
    pName = value
End Property
Public Property Get parent() As cProject
    parent = pParent
End Property
Public Property Let parent(value As cProject)
    pParent = value
End Property

这是一个标准模块:

Sub test1()

Dim cS As cScenarios
Dim s As cScenario

Set cS = New cScenarios

For i = 1 To 3
    Set s = New cScenario
    s.name = "s" & i
    cS.Add s
Next

Debug.Print cS.Item(3).name
Debug.Print cS.Count

End Sub

这行得通。一切都很好。目前。我能够用多种场景填充 cS。但是,如果我将场景集合作为项目的子对象引用(参见下面的 test2() ),我会在 cs.cs 上触发“运行时错误'91':对象变量或未设置块变量”。添加通话。

Sub test2()

Dim p As cProject
Dim cS As cScenarios
Dim s As cScenario

Set p = New cProject
Set cS = p.Scenarios

For i = 1 To 3
    Set s = New cScenario
    s.name = "s" & i
    cS.Add s
Next

Debug.Print cS.Item(3).name
Debug.Print cS.Count

End Sub

我在构建班级模块时做错了什么和/或如何修复它?谢谢。

4

1 回答 1

1

pScenarios在尝试cProject使用Add(). 您可以通过向以下位置添加初始化程序来解决此问题cProject

Private Sub Class_Initialize()
    Set pScenarios = New cScenarios
End Sub

这将保证cS实例不会Nothing在您尝试Add在其内部调用时出现test2。另一种方法(较弱的 IMO)是在内部p.Scenarios = new cScenarios更新后设置。另外,请确保属性设置器是而不是.ptest2cScenario.parentProperty SetProperty Let

于 2012-08-30T19:10:20.853 回答