如何在VBA中对自定义对象数组进行排序?

时间:2015-11-17 16:44:17

标签: arrays vba sorting

我的自定义对象:

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

1 个答案:

答案 0 :(得分: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