Return to VBA Code Examples

VBA Sort Array

This tutorial will demonstrate how to Sort values in an Array in VBA

Sorting a One-Dimensional Array using a loop

Sorting an Array requires a bit of data manipulation using loops, variables and temporary arrays.

  • You first need to populate the array with your values
  • You then need to loop through the array twice!  Once to get a value from the current element array, and the while still in that loop, to get the value of the next element in the array.
  • You then need to compare the elements – and move the 2nd one to the position of the first one if the 2nd one is alphabetically BEFORE the 1st one.

The example below demonstrates this procedure.

If you run this procedure, you would get the following message box.

vba sort array forwards

You can also sort the array in the other direction – eg: Z to A by changing this line of code

to this line of code

You would then get the following message box.

vba sort array backwards

 

 

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users! vba save as


Learn More!