PDA

View Full Version : [SOLVED:] Stuck on sorting array



straw
09-14-2023, 11:29 PM
Hi there! I am self-learning excel vba recently following online materials. Now I am learning sorting array (with nested loop). There is something I couldn't figure it out.
Could any one tell me what the difference between this two codes? Both of them got the same result. I've tried to study it for a day but still can't understand the concept. Thank you!

Answer from the materials:


For j = i + 1 To UBound(myArray) '
If UCase(myArray(i)) > UCase(myArray(j)) Then
Temp = myArray(j)
myArray(j) = myArray(i)
myArray(i) = Temp
End If

Tested by myself:

For j = i + 1 To UBound(myArray)
If UCase(myArray(i)) > UCase(myArray(j)) Then
Temp = myArray(i)
myArray(i) = myArray(j)
myArray(j) = Temp
End If

The full code is below:


Sub vba_sort_array()
Dim myArray() As Variant
ReDim myArray(5)
Dim i As Integer
Dim j As Integer
Dim Temp As String
myArray(1) = "E"
myArray(2) = "D"
myArray(3) = "C"
myArray(4) = "B"
myArray(5) = "A"
MsgBox LBound(myArray)
MsgBox UBound(myArray)
'sorting array from A to Z
For i = LBound(myArray) To UBound(myArray)
For j = i + 1 To UBound(myArray) '
If UCase(myArray(i)) > UCase(myArray(j)) Then
Temp = myArray(j)
myArray(j) = myArray(i)
myArray(i) = Temp
End If
' For j = i + 1 To UBound(myArray)
' If UCase(myArray(i)) > UCase(myArray(j)) Then
' Temp = myArray(i)
' myArray(i) = myArray(j)
' myArray(j) = Temp
' End If
'Next j
Next i
Debug.Print myArray(1)
Debug.Print myArray(2)
Debug.Print myArray(3)
Debug.Print myArray(4)
Debug.Print myArray(5)
End Sub

Aflatoon
09-15-2023, 03:55 AM
There is no functional difference; both of them swap the items around. The only change is which one is put into a temporary variable while you assign the other to its place.

Paul_Hossler
09-15-2023, 11:03 AM
Sorry, couldn't resist some comments and tweaks :whistle:



Sub vba_sort_array()
Dim myArray() As Variant

ReDim myArray(1 To 5) ' other wise starts at 0 (unless you have Option Base 1 set (homework assignment ))
Dim i As Integer
Dim j As Integer
Dim Temp As String

myArray(1) = "E"
myArray(2) = "D"
myArray(3) = "C"
myArray(4) = "B"
myArray(5) = "A"

MsgBox LBound(myArray) & " - " & UBound(myArray)

'sorting array from A to Z
For i = LBound(myArray) To UBound(myArray) - 1 ' added the -1
For j = i + 1 To UBound(myArray) '
If UCase(myArray(i)) > UCase(myArray(j)) Then
Temp = myArray(j)
myArray(j) = myArray(i)
myArray(i) = Temp
End If
Next j
Next i

Debug.Print myArray(1)
Debug.Print myArray(2)
Debug.Print myArray(3)
Debug.Print myArray(4)
Debug.Print myArray(5)
End Sub

straw
09-17-2023, 09:13 PM
Thank you for your explanation! :thumb:thumb