Search code examples
arraysvbasortingbubble-sort

vba How to Bubble Sort with two Criteria


I have an Array of txt like this:

  • "Unique text |05||001|"
  • "Unique text |04||001|"
  • "Unique text |05||002|"
  • "Unique text |04||002|"
  • "Unique text |05||003|"
  • "Unique text |08||003|"
  • "Unique text |04||003|"
  • "Unique text |05||004|"

I have managed to sort this array with bubble Sort, choosing the 2nd set of numbers "001,001,002,002,003...." But i will also like to sort with the first set of numbers as well. Result like this:

  • "Unique text |04||001|"
  • "Unique text |05||001|"
  • "Unique text |04||002|"
  • "Unique text |05||002|"
  • "Unique text |04||003|"
  • "Unique text |05||003|"
  • "Unique text |08||003|"
  • "Unique text |05||004|"

Any idea of how I could structure my bubble sort? Do i need at new For loop inside my regulare bubble sort?

Current Code (This will Only sort based on 2nd set of numbers). 104 = position of last set of numbers

    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

Solution

  • The key to the solution is the compare function:

    There are 2 main ways to do this: The first and the most simple is - to create a new number and sort by it

    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|"
    

    More correct and a bit more complicated to do is to simply do 2 compares:

    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
    

    Where getParam is function that takes "Unique text |04||002|" and returns "04" or "002".