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
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