Article ID: 213818 - View products that this article applies to.
This article was previously published under Q213818
In Microsoft Excel 2000, there is no direct method for sorting an array of values with a Microsoft Visual Basic for Applications macro or procedure. This article discusses two different algorithms that you can use to sort arrays: the Selection Sort and the Bubble Sort.
Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability and/or fitness for a particular purpose. This article assumes that you are familiar with the programming language being demonstrated and the tools used to create and debug procedures. Microsoft support professionals can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific needs.
If you have limited programming experience, you may want to contact a Microsoft Certified Partner or Microsoft Advisory Services. For more information, visit these Microsoft Web sites:
Microsoft Certified Partners - https://partner.microsoft.com/global/30000104
Microsoft Advisory Services - http://support.microsoft.com/gp/advisoryservice
For more information about the support options that are available and about how to contact Microsoft, visit the following Microsoft Web site: http://support.microsoft.com/default.aspx?scid=fh;EN-US;CNTACTMS
Method 1: Selection SortAlthough a Selection Sort is among the easier of sorts to program, it tends to run more slowly than the Bubble Sort on large arrays of data.
To perform a Selection Sort of an array with between 1 to n number of elements, locate the largest element from 1 to n. If this is not element n, exchange the largest element with element n. Then, locate the largest element from 1 to n-1 and, if this is not element n-1, exchange the largest element with element n-1. Next, locate the largest element from 1 to n-2 and, if this is not element n-2, exchange the largest element with element n-2, and so on.
The following is an example of a Selection Sort with a Visual Basic Variant type array.
Method 2: Bubble SortA Bubble Sort is more difficult to program than the Selection Sort, but it tends to run faster and more efficiently with larger arrays of data.
To perform a Bubble Sort, evaluate 1 to n-1 elements in the array where you compare each element with the one after it (in other words, element 1 is compared to element 2, element 2 is compared to element 3, and so on). If an element is larger than the element after it, those two elements are exchanged. Continue this process until there are no more exchanges of elements. The following is an example of a Bubble Sort with a Visual Basic Variant type array.
To perform a Bubble Sort in descending order, change ">" to a "<" in the following line of the BubbleSort function: