2015-01-20 64 views
0

我一直在尝试创建一个类(另一个类的对象)的集合,这是在父类中。我在这里看过几个问题,但无法正常工作。所以如果任何人都可以用我的参数发布一个短代码,我会非常感激。Excel VBA - 在父类中创建一个集合类

我的父类是Sample。它应该包含一个SampleFields集合,它应该包含类SampleField中的对象。 SampleField对象只有一个Name属性,它取自单元格A1到D1。应该可以添加和删除SampleFields集合中的项目并修改SampleField对象的Name属性。 SampleFields集合在Sample类的初始化时获取它的对象。

我需要访问它像这样 - Sample.SampleFields(1)请将.Name

我认为这是没用的,后我的尝试,但在这里它是:

Sub test() 

Dim a As New Sample, i As Variant 

a.GetFields 

For Each i In a.SampleFields 
    Debug.Print i.Name 
Next 

End Sub 

Sample类:

Private pFields As New SampleFields 

Public Property Get SampleFields() As SampleFields 
    Set SampleFields= pFields 
End Property 

Public Property Set SampleFields(ByVal value As SampleFields) 
    Set pFields = value 
End Property 

Private Sub Initialize_Class() 
    Set pFields = New SampleFields 
End Sub 


Public Sub GetFields() 

Dim rngHeaders As Range, rngCell As Range 
Set rngHeaders = Range("A1").CurrentRegion.Rows(1) 

For Each rngCell In rngHeaders.Cells 
    Dim newField As SampleField 
    newField.Name = rngCell.Value2 
    Me.Fields.AddNewField (newField) 'crashes here with Method or data member not found 
Next 

End Sub 

SampleFields类:

Private pFields As New Collection 

Public Sub AddNewField(FieldName As SampleField) 
    Me.AddNewField (FieldName) 
End Sub 

SampleField等级:

Private pName As String 

Public Property Let Name(value As String) 
    pName = value 
End Property 

Public Property Get Name() As String 
    Name = pName 
End Property 

谢谢!

+1

请通过提供的代码添加更多的细节段,您正在研究和明确确定有问题的部分。最好的问候, – 2015-01-20 18:59:51

+0

私人pFields作为新的收藏和私人pFields由于新的SampleFields似乎模棱两可。顺便说一句,为什么你需要一个Collection类,如果它已经是Excel VBA中的内置对象? – 2015-01-20 19:39:30

+0

除了内置集合之外,我可能还需要一些集合的自定义属性/方法。 – jivko 2015-01-20 19:50:11

回答

0

非常旧的帖子,但让我至少回答这个: 在示例类中,有一个集合。你可以忘记SampleFields类,它不是必需的。

然后,您只需要将一个SampleField类传递给此SampleClass方法“AddField”,用于增加集合的大小。

Sample类应该是这样的:

Private p_SampleFields as Collection 
Private p_SampleField as SampleField 

'Initialize this class with it's collection: 
Private Sub Class_Initialize() 
    Set p_SampleFields = New Collection 
End Sub 

'Allow for adding SampleFields: 
Public Sub AddField(field as SampleField) 
    Set p_SampleField = field 
    p_sampleFields.add field 
End Sub 

'Expose the collection: 
Public Property Get SampleFields() as Collection 
    Set SampleFields = p_SampleFields 
End Property 

在常规的模块,那么你可以使用以下命令:

Sub Test() 
    Dim sField as SampleField 
    Dim sClass as SampleClass 

    Set sField = New SampleField 
    Set sClass = New SampleClass 

    sField.Name = "SomeName" 
    sClass.AddField sField 'This adds it to the collection 

    'Access as per requirement: 
    msgbox sClass.SampleFields(1).Name 'Pop-up saying "SomeName" 
End Sub 
相关问题