Situation:
1. First, we declare four variables. One variable of type String we call TempString, one variable of type Integer we call TempInteger, one variable of type Integer we call i, and one variable of type Integer we call j.
Dim tempString As String, tempInteger As Integer, i As Integer, j As Integer2. We write 5 random numbers to column B (one for each name). We use the worksheet function RandBetween for this.
For i = 1 To 5Result so far:
Cells(i, 2).Value = WorksheetFunction.RandBetween(0, 1000)
Next i
We will use the numbers next to each name to sort the names. The name with the lowest number first, the name with the second lowest number, second, etc.
3. We start a Double Loop.
For i = 1 To 54. Add the following code line:
For j = i + 1 To 5
If Cells(j, 2).Value < Cells(i, 2).Value ThenExample: for i = 1 and j = 2, Wendy and Richard are compared. Because Richard has a lower number, we swap Wendy and Richard. Richard is at the first position now. For i = 1 and j = 3, Richard and Joost are compared. Joost has a higher number so nothing happens. This way, Excel VBA gets the name with the lowest number at the first position. For i = 2, Excel VBA gets the name with the second lowest number at the second position, etc.
5. If true, we swap the names.
tempString = Cells(i, 1).Value6. And we swap the numbers.
Cells(i, 1).Value = Cells(j, 1).Value
Cells(j, 1).Value = tempString
tempInteger = Cells(i, 2).Value7. Don't forget to close the If statement.
Cells(i, 2).Value = Cells(j, 2).Value
Cells(j, 2).Value = tempInteger
End If8. Don't forget to close the two loops.
Next j9. Test the program.
Next i
Result:
Note: you can add a line which deletes the numbers in column B. It's even nicer to place the numbers of each name in an array, so no numbers are placed on your worksheet. However, for illustrative purpose we've chosen to place the values on the sheet..