une

I have have an array named punc, is there a function I can use to sort its elements

Would the command be;

Array.Sort(punc)

it doesn't seem to work.

This code did not work either and I can't work out why;

Dim punc(3) As Integer

punc(0) = 8
punc(1) = 7
punc(2) = 6
punc(3) = 5

Dim i As Integer
Dim j As Integer
Dim temp As Integer
For i = 0 To 3 Step 1
For j = 0 To 2 Step 1
If punc(j) > punc(j + 1) Then
temp = punc(j + 1)
punc(j + 1) = punc(j)
punc(j) = temp
End If
Next j
Next i

### Re: Sorting an array

Andy Pope

Hi,

This is no built-in array object type with sort methods.

You would have to sort the array yourself, as you are doing.

What exactly does not work with your code

Sub x()
Dim i As Integer
Dim j As Integer
Dim temp As Integer
Dim punc(3) As Integer

For i = 0 To 3
punc(i) = 10 - i
Debug.Print "punc("; i; ")="; punc(i)
Next

For i = 0 To 3 Step 1
For j = 0 To 2 Step 1
If punc(j) > punc(j + 1) Then
temp = punc(j + 1)
punc(j + 1) = punc(j)
punc(j) = temp
End If
Next j
Next i

Debug.Print "Sorted"
For i = 0 To 3
Debug.Print "punc("; i; ")="; punc(i)
Next

End Sub

### Re: Sorting an array

une

It is strange as when I create the code as a Sub and call it from another Sub it doesn't work. So I just transplated all the sorting code into the parent Sub and it works fine. Maybe something to do with ByRef

The following just does not sort the array and I cannot work out why;

Public Sub sort()

Dim punc(3) As Integer

punc(0) = 8
punc(1) = 7
punc(2) = 6
punc(3) = 5
MsgBox punc(0) & " " & punc(1) & " " & punc(2) & " " & punc(3)
SortArray (punc)
MsgBox punc(0) & " " & punc(1) & " " & punc(2) & " " & punc(3)
' It has not been sorted and I don't know why
End Sub

Private Sub SortArray(ByRef arrayName As Variant)

Dim i As Integer
Dim j As Integer
Dim temp As Integer

For i = 0 To UBound(arrayName)
For j = 0 To UBound(arrayName) - 1
If arrayName(j) > arrayName(j + 1) Then
temp = arrayName(j + 1)
arrayName(j + 1) = arrayName(j)
arrayName(j) = temp
End If
Next j
Next i

End Sub

### Re: Sorting an array

Andy Pope

Not the ByRef rather the use of paranthesis on the array when you call the routine.