vbaexcelex

Add Object to beginning of collection VBA


This may have been asked before but I can't seem to find it...

I have a class I created and a collection for each object of that class, when I added these objects to my collection I did not give each item a key and rather let VBA do that automatically.

Code below doesn't seem to work for me...

ediData.StyleCollection.Add StoreStyleData(Range("A" & i & ":M" & i)), Before:=0

Tried this as well and not working either!

ediData.StyleCollection.Add StoreStyleData(Range("A" & i & ":M" & i)), Before:=1

QUESTION:

How can I add an item to the beginning of a collection rather than the end? If I can't do that, how can I loop through a collection from the end instead of the start of it?

EDIT:

Below I've included the Function for StoreStyleData

Private Function StoreStyleData(rng As Range) As cPOStyle

   Set StoreStyleData = New cPOStyle
   With rng
      StoreStyleData.XRef = .Cells(1).value
      StoreStyleData.Season = .Cells(2).value
      StoreStyleData.Style = .Cells(3).value
      StoreStyleData.Color = .Cells(4).value
      StoreStyleData.Size = .Cells(5).value
      StoreStyleData.RetailPrice = .Cells(6).value
      StoreStyleData.Category = .Cells(8).value
      StoreStyleData.PO850Price = .Cells(9).value
      StoreStyleData.XRefPrice = .Cells(10).value
      StoreStyleData.Units = .Cells(11).value
      StoreStyleData.SubTotal = .Cells(12).value
      StoreStyleData.Description = .Cells(13).value
   End With

End Function

COLLECTION WITHIN THE CLASS

''''''''''''''''''''''
' StyleCollection Property
''''''''''''''''''''''
Public Property Get StyleCollection() As Collection
   If pStyleCollection Is Nothing Then Set pStyleCollection = New Collection
   Set StyleCollection = pStyleCollection
End Property
Public Property Let StyleCollection(value As Collection)
   Set pStyleCollection = value
End Property

Solution

  • Maybe try:

    StyleCollection.Add Item:=StoreStyleData(Range("A" & i & ":M" & i)), Before:=1
    

    Does the below allow you to loop through collection backwards:

    For i = StyleCollection.Count to 1 Step -1
    
    'Debug.print StyleCollection.Items(i) or StyleCollection(i)
    
    Next i
    

    Untested, written on mobile.

    Edit 1:

    If StyleCollection.Count > 0 then
    
    StyleCollection.Add Item:=StoreStyleData(Range("A" & i & ":M" & i)), Before:=1
    
    Else
    
    StyleCollection.Add StoreStyleData(Range("A" & i & ":M" & i))
    
    End if