Microsoft Office Tutorials and References
In Depth Information
A Realistic Example That Uses Sub Procedures
Here’s the sorting procedure I developed (after consulting a few programming Web sites to get
some ideas):
Sub BubbleSort(List() As String)
‘ Sorts the List array in ascending order
Dim First As Long, Last As Long
Dim i As Long, j As Long
Dim Temp As String
First = LBound(List)
Last = UBound(List)
For i = First To Last - 1
For j = i + 1 To Last
If List(i) > List(j) Then
Temp = List(j)
List(j) = List(i)
List(i) = Temp
End If
Next j
Next i
End Sub
This procedure accepts one argument: a one-dimensional array named List . An array passed to
a procedure can be of any length. I used the LBound and UBound functions to assign the lower
bound and upper bound of the array to the variables First and Last , respectively.
Here’s a little temporary procedure that I used to test the BubbleSort procedure:
Sub SortTester()
Dim x(1 To 5) As String
Dim i As Long
x(1) = “dog”
x(2) = “cat”
x(3) = “elephant”
x(4) = “aardvark”
x(5) = “bird”
Call BubbleSort(x)
For i = 1 To 5
Debug.Print i, x(i)
Next i
End Sub
The SortTester routine creates an array of five strings, passes the array to BubbleSort , and
then displays the sorted array in the Immediate window. I eventually deleted this code because it
served its purpose.
Search JabSto ::

Custom Search