Sorting an Array : Array « Data Type « VBA / Excel / Access / Word






Sorting an Array

 
   Option Explicit
   Option Base 1
 
   Sub Sort_an_Array()
       Dim strArray(12) As String
       Dim strTemp As String
       Dim X As Integer, Y As Integer, i As Integer

      strArray(1) = "n"
      strArray(2) = "d"
      strArray(3) = "h"
      strArray(4) = "g"
      strArray(5) = "e"
      strArray(6) = "d"
      strArray(7) = "o"
      strArray(8) = "p"
      strArray(9) = "m"
      strArray(10) = "h"
      strArray(11) = "b"
      strArray(12) = "m"

      Debug.Print "Current items in array:"
      For i = 1 To UBound(strArray)
          Debug.Print strArray(i)
      Next i

      For X = LBound(strArray) To (UBound(strArray) - 1)
          For Y = (X + 1) To UBound(strArray)
              If strArray(X) > strArray(Y) Then
                  strTemp = strArray(X)
                  strArray(X) = strArray(Y)
                  strArray(Y) = strTemp
                  strTemp = ""
              End If
          Next Y
      Next X

      Debug.Print "Items in sorted array:"
      For i = 1 To UBound(strArray)
          Debug.Print strArray(i)
      Next i
  End Sub

 








Related examples in the same category

1.Get the element in an array by index
2.Declaring a static array is similar to declaring a variable
3.Override the Option Base setting by specifically setting the lower bound in the array declaration
4.Declaring and Working with Fixed Arrays
5.Declaring array and setting bounds
6.Arrays are typically initialized inside a loop
7.Use the For Each...Next to assign value to an array
8.Use count function to count array
9.Use count function to sum array
10.Using a One-Dimensional Array
11.Define and use multidimensional array
12.Create an Array, assign value and use Loop to show its value
13.Use LBound and UBound in for statement
14.Using a Two-Dimensional Array and Reference its elements
15.Understanding Errors in Arrays
16.Function Parameter type: Array
17.Assign range to an array
18.Declaring a static array is similar to declaring a variable, with one small exception
19.To assume that 1 is the lower index for your arrays
20.Multidimensional arrays
21.Sorts the List array in ascending order
22.Searching through an Array
23.Fill array by using a nested For- Next loop.
24.Referencing Elements in a Multi-dimensional Array
25.Convert number to String by using Array
26.Specifying the Index Range of an Array