Hi all -
I am learning VBA and need some help understanding how the following code is able to organize an array of strings in alphabetical order. With regard to the For...Next section of code, I'd like to understand how checking if strArray(X) > strArray (Y) results in an alphabetized list. I'm also confused by the assignments - what does it mean when strTemp = strArray(X) and yet in the very next line of code strArray(X) = strArray(Y), and so on. If someone could explain in words how this section alphabetizes the array I'd really appreciate it. Thanks!
________________________________________________________________________________________________________________________
Option Explicit
Option Base 1
Sub Sort_an_Array()
'declare the array and other variables
Dim strArray(12) As String
Dim strTemp As String
Dim strMsg As String
Dim X As Integer, Y As Integer, i As Integer
'assign strings to the array
strArray(1) = "nihilism"
strArray(2) = "defeatism"
strArray(3) = "hope"
strArray(4) = "gloom"
strArray(5) = "euphoria"
strArray(6) = "despondency"
strArray(7) = "optimism"
strArray(8) = "pessimism"
strArray(9) = "misery"
strArray(10) = "happiness"
strArray(11) = "bliss"
strArray(12) = "mania"
strMsg = "Current items in array:" & vbCr & vbCr
For i = 1 To UBound(strArray)
strMsg = strMsg & i & ":" & vbTab & strArray(i) & vbCr
Next i
MsgBox strMsg, vbOKOnly + vbInformation, "Array Sorting: 1"
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
strMsg = "Items in sorted array:" & vbCr & vbCr
For i = 1 To UBound(strArray)
strMsg = strMsg & i & ":" & vbTab & strArray(i) & vbCr
Next i
MsgBox strMsg, vbOKOnly + vbInformation, "Array Sorting: 2"
End Sub
Bookmarks