我实现了一个类对象的集合。我从在线文章中获得了有关如何创建类对象集合的说明,但我并不完全理解。我的收藏作品。我可以将对象添加到 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