2015-11-17 50 views
0

我的自定義對象:如何在VBA中排序自定義對象數組?

clsCAN:

Public ntc_id As String 
Public grp_id As String 
Public sat_name As String 
Public freq_min As Long 
Public freq_max As Long 
Public ntc_type As String 

我要排序,按升序排列,通過freq_max

+0

您可能需要多發一些,以便我們瞭解您的對象。這是類模塊的一部分嗎? – R3uK

+1

這些只是代碼的變量? – newguy

+0

這是你的班級數組嗎?所以a()作爲clsCAN? –

回答

0

VBA-Collection的一類,並添加自己Sort方法。這裏用冒泡排序的簡單例子。泡泡排序很容易編寫,但只有少量未排序的數據才能正常運行,所以如果您在未排序的集合中有很多項目,這可能會非常慢! HTH。

clsCANs類模塊

Option Explicit 

Private list As Collection 

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

Public Property Get Count() As Long 
    Count = list.Count 
End Property 

Public Sub Add(ByVal newItem As clsCAN) 
    On Error GoTo ErrAdd 
    list.Add newItem 
ErrAdd: 
    Exit Sub 
    Err.Raise Err.Number, "clsCANs::Add", Err.Description 
End Sub 

Public Property Get Item(ByVal index As Integer) As clsCAN 
    On Error GoTo ErrItem 
    Set Item = list.Item(index) 
    Exit Property 
ErrItem: 
     Err.Raise Err.Number, "clsCANs::Item", Err.Description 
    End Property 

Public Sub Sort() 
    Dim swapOccured As Boolean 
    Dim i As Integer 
    Dim temp As clsCAN 

    Do 
     swapOccured = False 

     For i = 1 To list.Count - 1 
      If list.Item(i).freq_max > list.Item(i + 1).freq_max Then 

       ' swap to achieve ascending order 
       Set temp = list.Item(i) 
       list.Remove i 
       list.Add temp, , After:=i 

       swapOccured = True 

      End If 
     Next i 

    ' sorting has to continue while some swap was performed 
    Loop While swapOccured 

End Sub 

標準模塊

Option Explicit 

Sub test() 
    Dim itm As clsCAN 
    Dim col As clsCANs 

    Set col = New clsCANs 

    Set itm = New clsCAN 
    itm.freq_max = 3 
    itm.sat_name = "sat_3" 
    col.Add itm 

    Set itm = New clsCAN 
    itm.freq_max = 7 
    itm.sat_name = "sat_7" 
    col.Add itm 


    Set itm = New clsCAN 
    itm.freq_max = 4 
    itm.sat_name = "sat_4" 
    col.Add itm 

    ' etc for next items 

    col.Sort 

    Dim i As Integer 
    For i = 1 To col.Count 
     Debug.Print col.Item(i).sat_name 
    Next i 
End Sub 

注:採集包裝是從here