Article ID: 133135 - Last Review: October 11, 2006 - Revision: 2.3 Using a Visual Basic Macro to Sort Arrays in Microsoft Excel
This article was previously published under Q133135 For a Microsoft Excel 2000 version of this article, see 213818
(http://support.microsoft.com/kb/213818/EN-US/
)
.
On This PageSUMMARY
In Microsoft Excel, 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: Selection Sort and Bubble Sort.
MORE INFORMATIONMicrosoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers 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 requirements. Method 1: Selection SortTo perform a Selection Sort of an array with 1...n elements, locate the largest element from 1...n. If this is not element n, then exchange the largest element with element n. Then, locate the largest element from 1...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...n-2 and, if this is not element n-2, exchange the largest element with element n-2, and so on. Below is an example of a Selection Sort with a Visual Basic Variant type array.
Method 2: Bubble SortTo perform a Bubble Sort, evaluate 1...n-1 elements in the array where you compare each element with the one after it (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, then those two elements are exchanged. Continue this process until there are no more exchanges of elements. Below is an example of a Bubble Sort with a Visual Basic Variant type array.
APPLIES TO
| Other Resources Other Support Sites
CommunityGet Help NowArticle Translations
|






Windows Live
Facebook
Twitter
Linkedin
Digg it
Yahoo
Delicious
StumbleUpon
Yammer
Reddit
Technorati
FriendFeed
Email

Back to the top
