簡體   English   中英

arrays 的冒泡排序集合(VBA)

[英]Bubble sort Collection of arrays (VBA)

幾乎沒有 VBA 的經驗。請幫忙弄清楚我做錯了什么。 數據庫是一個集合,其中每個元素都是一個包含 5 個字符串類型元素的數組,描述了一些 object。我正在嘗試按數組的特定元素對集合進行排序。 在這段代碼中得到“運行時錯誤 13。類型不匹配”。

昏暗數據庫作為新集合

For i = 1 To DataBase.Count - 1
    For j = i + 1 To DataBase.Count
        If DataBase.Item(i)(1) > DataBase.Item(j)(1) Then
         temp = DataBase(j)
         DataBase.Remove (j)
         DataBase.Add temp, temp, i
        End If
    Next j
Next i

嘗試使用 Collection.Item (Index) 和 Collection(Index) 訪問集合元素,但無法獲得已排序的集合。

按每個數組的第一個元素對相同大小的 Arrays 的集合進行排序

快速修復

            If DataBase(i)(1) > DataBase(j)(1) Then
                Temp = DataBase(j)
                DataBase.Remove j ' redundant parentheses
                DataBase.Add Temp, , i ' the cause of the type mismatch
            End If

詳細說明(一個工作示例)

Option Explicit

Sub CollSort()

    Const collCount As Long = 10
    Dim Strs(): Strs = Array("G", "C", "D", "F", "H", "B", "E", "I", "J", "A")
    
    ' Populate the collection with the arrays, and each array's first element
    ' using the strings from the 'Strs' array.
    
    Dim coll As Collection: Set coll = New Collection
    Dim arr() As String: ReDim arr(1 To 5)
    
    Dim n As Long
    
    For n = 1 To collCount
        arr(1) = Strs(n - 1)
        coll.Add arr
    Next n
    
    ' Print populated data (only the first element of each array).
    
    Dim Item As Variant
    
    Debug.Print "Initial"
    For Each Item In coll
        Debug.Print Item(1)
    Next Item

    ' Bubble sort by the first element of each array.
    ' Note that the arrays are being swapped, not their first elements.

    Dim Temp, i As Long, j As Long

    For i = 1 To coll.Count - 1
        For j = i + 1 To coll.Count
            If coll(i)(1) > coll(j)(1) Then
                Temp = coll(j)
                coll.Remove j
                coll.Add Temp, , i
            End If
        Next j
    Next i

    ' Print sorted data (only the first element of each array).
    
    Debug.Print "Sorted"
    For Each Item In coll
        Debug.Print Item(1)
    Next Item

End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM