Search code examples
excelvbabubble-sort

Bubble Sort in VBA isn't sorting correctly


I am trying to bubble sort some data and it the sorting isn't working. I think I have to be doing something obviously silly. I have followed the code close enough to know it is something wrong with the actually sorting alg.

        Do While Low <= High And Worksheets("Data").Cells(i, Column_EAM_WorkOrderNum) <> ""
            CheckVal = (High + Low) / 2
            If Worksheets("Data").Cells(i, Column_EAM_WorkOrderNum) = Worksheets("Data2").Cells(CheckVal, Column_KSR_WorkOrderNum) Then
               'Copy Data Over
                Worksheets("Data").Range("AM1").Offset(i - 1, 0).Value = Worksheets("Data2").Range("A1").Offset(CheckVal - 1, Column_KSR_ServiceID - 1).Value
                Worksheets("Data").Range("AN1").Offset(i - 1, 0).Value = Worksheets("Data2").Range("A1").Offset(CheckVal - 1, Column_KSR_CreatedDate - 1).Value
'
                If IsNumeric(Column_KSR_Type) = True Then
                    Worksheets("Data").Range("AO1").Offset(i - 1, 0).Value = Worksheets("Data2").Range("A1").Offset(CheckVal - 1, Column_KSR_Type - 1).Value
                End If
                Exit Do
            ElseIf Worksheets("Data").Cells(i, Column_EAM_WorkOrderNum) < Worksheets("Data2").Cells(CheckVal, Column_KSR_WorkOrderNum) And Worksheets("Data2").Cells(CheckVal, Column_KSR_WorkOrderNum) <> "Service Provider Ref #" Then
                Low = CheckVal - 1
            Else
                High = CheckVal + 1
            End If
        Loop

I apologize in advance: Do to how this code is setup I couldn't figure out an easy way to provide the minimal reproduceable code without copying in hundreds of lines of code to support this one simple block. I'm hoping I'm just missing something obvious.


Solution

  • Swap your Low and High in ElseIf and Else.