vba 如何使用两个条件进行冒泡排序

vba How to Bubble Sort with two Criteria

我有一个这样的 txt 数组:

我已经设法用冒泡排序对这个数组进行排序,选择第二组数字“001,001,002,002,003 ....”,但我也想用第一组数字排序。结果是这样的:

知道如何构建冒泡排序吗? 我需要在我的常规冒泡排序中使用新的 For 循环吗?

当前代码(这将仅根据第二组数字排序)。 104 = 最后一组数字的位置

    For i = 1 To UbndCellDataExcel - 1
      For j = i + 1 To UbndCellDataExcel
        If Mid(CellDataExcel(i), 104, 3) > Mid(CellDataExcel(j), 104, 3) Then   
            strTemp = CellDataExcel(i)
            CellDataExcel(i) = CellDataExcel(j)
            CellDataExcel(j) = strTemp
        End If
      Next j
    Next i

解决的关键是比较函数:

主要有两种方法: 第一个也是最简单的是 - 创建一个新数字并按它排序

convert "Unique text |05||001|" to "00105"
convert "Unique text |04||002|" to "00204"
00204>00105 so "Unique text |04||002|" > "Unique text |05||001|"

更正确和更复杂的做法是简单地进行 2 次比较:

Function compare (ByVal i As String,ByVal j As String)
    i1=getParam(1,i)
    i2=getParam(2,i)
    j1=getParam(1,j)
    j1=getParam(2,j)
    if (i1>j1) return 1
    if (i2<j2) return -1
    if (j1>j1) return 1
    if (j2<j2) return -1
    return 0

其中 getParam 是接受 "Unique text |04||002|" 和 returns“04”或“002”的函数。

谢谢 מתן ל !这是我现在根据你的想法实现的转换:

convert "Unique text |05||001|" to "00105"
convert "Unique text |04||002|" to "00204"

我的代码现在看起来像这样(100 = 第一组数字的位置,104 是第二组数字):

    For i = 1 To UbndCellDataExcel - 1
    For j = i + 1 To UbndCellDataExcel
        If Mid(CellDataExcel(i), 104, 3) & Mid(CellDataExcel(i), 100, 2) > Mid(CellDataExcel(j), 104, 3) & Mid(CellDataExcel(j), 100, 2) Then   'Sorter basert på OUnr
            strTemp = CellDataExcel(i)
            CellDataExcel(i) = CellDataExcel(j)
            CellDataExcel(j) = strTemp
        End If
    Next j
Next i


'Mid(CellDataExcel(i), 104, 3) & Mid(CellDataExcel(i), 100, 2) returns Format: "00105"