将Object添加到集合VBA的开头

时间:2017-12-29 18:51:29

标签: vba excel-vba ex excel

之前可能已经提出这个问题,但我似乎无法找到它......

我有一个我创建的类和该类的每个对象的集合,当我将这些对象添加到我的集合中时,我没有给每个项目一个键,而是让VBA自动完成。

下面的代码似乎对我不起作用......

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

也试过这个,也没办法!

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

问题:

如何将项目添加到集合的开头而不是结尾?如果我不能这样做,我如何从最终而不是从头开始循环收集?

修改

下面我已经包含了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

在课堂上收集

''''''''''''''''''''''
' 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

2 个答案:

答案 0 :(得分:1)

也许试试:

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

以下是否允许您向后循环收集:

For i = StyleCollection.Count to 1 Step -1

'Debug.print StyleCollection.Items(i) or StyleCollection(i)

Next i

未经测试,写在手机上。

修改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

答案 1 :(得分:0)

如果您想先获得最后一项,请使用后退循环:

Dim x As Integer
Dim cls As New MyClass
Dim itm As Item
For x = MyClass.Items.Count To 1 Step -1
    Set itm = MyClass.Items(x)
Next

示例

WorkersCollection上课:

Private col As New Collection

Sub AddWorker(w As Worker)
    col.Add w
End Sub

Property Get Workers() As Collection
    Set Workers = col
End Property

Worker上课:

Private m_Name As String
Property Get Name() As String
    Name = m_Name
End Property
Property Let Name(v As String)
    m_Name = v
End Property

测试方法:

Sub Test()

    Dim w As Worker
    Dim x As Integer
    Dim wcol As New WorkersCollection

    For x = 1 To 5
        Set w = New Worker
        w.Name = "Name" & x
        wcol.AddWorker w
    Next

    For x = wcol.Workers.Count To 1 Step -1
        Debug.Print wcol.Workers(x).Name
    Next

    'Output:
    'Name5
    'Name4
    'Name3
    'Name2
    'Name1

End Sub