VBA Excel:如何使用收集密钥?

时间:2013-10-15 01:13:04

标签: class excel-vba collections vba excel

我实现了一个类对象的集合。我从如何在线文章中获得了如何创建类对象集合的说明,但我并不完全理解它。我的收藏有效。我可以向Coll添加对象,操纵他们的数据,并从其他函数中使用它们。

文章:http://www.cpearson.com/excel/CollectionClass.aspx

也许它只适用于VBA但不适用于VBA Excel?我经常被绊倒。

目前我只在集合中添加一种类型的对象,但添加各种对象类型会更有用。但是,当我浏览每个物体时,我不知道它们是什么类型。

CollKeys的第二个系列是什么?什么是钥匙?它是如何在Excel VBA中使用的?添加不同类型的对象会有帮助吗?

' Collection cCRE_Coll

Option Explicit
Private Const msMODULE As String = "cCRE_Coll"

' This is a collection of CRE objects
Private pCount As Long
Private Coll As Collection
Private CollKeys As Collection

  Private Sub Class_Initialize()
        Set Coll = New Collection
        Set CollKeys = New Collection
    End Sub

    Private Sub Class_Terminate()
        Set Coll = Nothing
        Set CollKeys = Nothing
    End Sub

Public Property Get Count() As Long
    pCount = Coll.Count
End Property

以下是我测试它的方法,但我需要进行更复杂的操作...

Sub testReadWrite()
    Dim collCRE As New Collection
    Dim collPE As New Collection
    Dim collPP As New Collection
    Dim clsCRE As cCRE
    Dim clsPE As cPE
    Dim clsPP As cPP

    Dim i As Long
    Dim myWS As Worksheet
    Dim lLastRow As Long

    Set myWS = ActiveSheet

    lLastRow = lFindNewRow(myWS) - 1
    ' Item count starts at 1

' Test reading in all the different types of row entries
    For i = giHEADER_ROW + 1 To lLastRow
    If myWS.Cells(i, ColNum.CRE_ID) <> vbNullString Then
        ' Read in a CRE
        Set clsCRE = New cCRE   ' Start with a blank clsCRE
        Call clsCRE.ReadFromWS(myWS, myWS.Cells(i, ColNum.CRE_ID))
        collCRE.Add clsCRE
    ElseIf StrComp(myWS.Cells(i, ColNum.PE_CRE_ID), gsPE_SUMMARY_TAG) = 0 Then
        ' Read in a PE/RCR (not a PP)
        Set clsPE = New cPE
        Call clsPE.ReadFromWS(myWS, myWS.Cells(i, ColNum.PE_ID))
        collPE.Add clsPE
    ElseIf StrComp(myWS.Cells(i, ColNum.PE_ID), gsPP_ID) = 0 Then
        Set clsPP = New cPP
        Call clsPP.ReadFromWS(myWS, i)
        collPP.Add clsPP
    ElseIf myWS.Cells(i, ColNum.PE_ID) = vbNullString Then
        Debug.Print "Cannot Read In Row " & i
    End If
    Next

' In the middle I will change, sort, add and remove objects.

' Test writing out all of the different types of row entries
    For Each clsCRE In collCRE
        Call clsCRE.WriteToWS(ThisWorkbook.Sheets("Sheet1"))
    Next

    For Each clsPE In collPE
        Call clsPE.WriteToWS(ThisWorkbook.Sheets("Sheet1"))
    Next

    For Each clsPP In collPP
        Call clsPP.WriteToWS(ThisWorkbook.Sheets("Sheet1"))
    Next

End Sub

0 个答案:

没有答案