简体   繁体   中英

How do i sort a custom-object array in VBA?

My custom object:

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

I want to sort, in ascending order, by freq_max

Wrap VBA-Collection in a class and add your own Sort method. Here simple example with bubble sort . Bubble sort is easy to write but can perform well only with small amount of unsorted data, so if you have a lot of items in unsorted collection this might be really slow! HTH.

clsCANs class module

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

standard module

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

Note: Collection wrapper is from here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM