Bubble Sort

Add to Favorites

This macro will perform a bubble sort in excel. You use it simply by selecting one column to sort and then running the macro.

This is basically just like a regular sort but just done using the bubble sort method of comparing two contiguous cells and then switching cell position between those two cells so that those two are arranged in a local ascending or descending order. This is then repeated until the entire sequence is sorted in the correct order. This type of sort takes more time than a quick sort or than many other types of sorts; however, it still works and is widely taught.

Note: If you want to sort in descending order, replace the "<" with a ">" sign in the line that reads "If Val(sortingArray(j, 1)) < Val(sortingArray(i, 1)) Then."

Where to install the macro:  Module

Bubble Sort Macro in Excel

Sub bubble_sort()

Dim sortingArray As Variant, i As Long, j As Long, temp As Variant

sortingArray = Selection.Value

For i = 1 To (UBound(sortingArray, 1) - 1)
   For j = i To UBound(sortingArray, 1)
      If Val(sortingArray(j, 1)) < Val(sortingArray(i, 1)) Then
         temp = sortingArray(i, 1)
         sortingArray(i, 1) = sortingArray(j, 1)
         sortingArray(j, 1) = temp
      End If
   Next j
Next i

Selection.Value = sortingArray
End Sub

How to Install the Macro
  1. Select and copy the text from within the grey box above.

  2. Open the Microsoft Excel file in which you would like the Macro to function.

  3. Press "Alt + F11" - This will open the Visual Basic Editor - Works for all Excel Versions.  Or For other ways to get there, Click Here.

  4. On the new window that opens up, go to the left side where the vertical pane is located. Locate your Excel file; it will be called VBAProject (YOUR FILE'S NAME HERE) and click this.

  5. If the Macro goes in a Module, Click Here, otherwise continue to Step 8.

  6. If the Macro goes in the Workbook or ThisWorkbook, Click Here, otherwise continue to Step 8.

  7. If the Macro goes in the Worksheet Code, Click Here, otherwise continue to Step 8.

  8. Close the Microsoft Visual Basic Editor window and save the Excel file. When you close the Visual Basic Editor window, the regular Excel window will not close.

  9. You are now ready to run the macro.

Subscribe for Free Excel tips & more!