XL: Using a Visual Basic Macro to Sort Arrays in Microsoft ExcelLast reviewed: February 3, 1998Article ID: Q133135 |
The information in this article applies to:
SUMMARYIn 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, 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 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 needs. If you have limited programming experience, you may want to contact the Microsoft fee-based consulting line at (800) 936-5200. For more information about the support options available from Microsoft, please see the following page on the World Wide Web:
http://www.microsoft.com/support/supportnet/refguide/default.asp 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.
MORE INFORMATIONNOTE: Both of these examples sort in ascending order. To perform a Selection Sort in descending order, change ">" to "<" in the following line of the SelectionSort function:
If TempArray(j) > MaxVal ThenTo perform a Bubble Sort in descending order, change ">" to a "<" in the following line of the BubbleSort function:
If TempArray(i) > TempArray(i + 1) Then |
Additional query words: 5.00 5.00a 5.00c 7.00 8.00 XL98 XL97 XL7 XL5
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |