Excel VBA:自定义集合重复项

时间:2015-01-22 18:24:35

标签: excel-vba vba excel

我创建了一个包含自定义集合类的类。初始化父类时,集合类将填充项目。问题是,当我遍历集合的项目时,所有项目都具有添加的最后一项的属性。这些项应与ActiveSheet中的单元格相关联,每个项目都具有“名称”和“范围”属性。 Name是单元格的值,Range是Range。因此在单元格A1:D1中我有值ID,Q1,Q2,Q3,当我创建父类的实例时,我希望集合的成员具有名称ID,Q1,Q2,Q3和范围A1,B1,C1 ,D1。然而,当我迭代时,输出显示Q3,Q3,Q3,Q3和$ D $ 1,$ D $ 1,$ D $ 1,$ D $ 1.

问题出在哪里?

以下代码:

Sub test()

    Dim Sample As Sample
    Set Sample = New Sample

    Dim fld As New Field

    For Each fld In Sample.Fields
        Debug.Print fld.Name; vbTab; fld.Range.Address
    Next

End Sub

Field类:

Private pName As String
Private pRange As Range

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

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

Public Property Set Range(rng As Range)
    Set pRange = rng
End Property

Public Property Get Range() As Range
    Set Range = pRange
End Property

Fields类(自定义集合):

Private pFields As Collection

Private Sub Class_Initialize()
    Set pFields = New Collection
End Sub

Private Sub Class_Terminate()
    Set pFields = Nothing
End Sub

Public Function NewEnum() As IUnknown
    Set NewEnum = pFields.[_NewEnum]
End Function

Public Sub Add(fld As Field)
    pFields.Add fld
End Sub

Public Sub Remove(Index As Variant)
    pFields.Remove Index
End Sub

Public Property Get Item(Index As Variant) As Field
    Set Item = pFields.Item(Index)
End Property

Property Get Count() As Long
    Count = pFields.Count
End Property

Public Sub Clear()
    Set pFields = New Collection
End Sub

Sample类(包含Fields集合类):

Private pFields As Fields

Private Sub Class_Initialize()
    Set pFields = New Fields
    Initialize_Fields
End Sub

Private Sub Class_Terminate()
    Set pFields = Nothing
End Sub

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

Private Sub Initialize_Fields()

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

    For Each rngCell In rngHeaders.Cells
        Dim NewField As New Field
        NewField.Name = rngCell.Value2
        Set NewField.Range = rngCell

        pFields.Add NewField
    Next rngCell

End Sub

1 个答案:

答案 0 :(得分:0)

问题解决了。

改变了这个:

For Each rngCell In rngHeaders.Cells
    Dim NewField As New Field
    NewField.Name = rngCell.Value2
    Set NewField.Range = rngCell

    pFields.Add NewField
Next rngCell

对此:

Dim NewField As Field

For Each rngCell In rngHeaders.Cells
    Set NewField = New Field

    NewField.Name = rngCell.Value2
    Set NewField.Range = rngCell

    pFields.Add NewField
Next rngCell