I have to write a function to sort a given range in VBA in Excel. (Bubble Sort) I have done the following :
Function MySort(M2 As Range)
    Dim r As Integer
    r = M2.Rows.Count
    Dim M1 as range
    M1 = M2
    Dim buffer
    For i = 0 To r
        For j = i To r
            If (M1.Item(i, 0) > M1.Item(j, 0)) Then
                buffer = M1.Item(i, 0)
                M1.Item(i, 0) = M1.Item(j, 0)
                M1.Item(j, 0) = buffer
            End If
        Next j
    Next i
    MySort = M1
End Function
Problems :
- it returns "#VALUE"
- I have tried converting the Range into an array
- if I do not cast M2 into M1 the function returns the list unsorted
- I have tried with basis 1 and with basis 0
I think I do have identified the main problem which is highlighted in the following example :
Function TestArray(M1 As Range)
    r = M1.Rows.Count
    Dim M2 As Range
    Dim M3()
    ReDim M3(r)
    M3 = M1
    M2 = M1
    TestArray = M3(0, 0) ' or M2.item(0, 0)
End Function
This function will return "#VALUE".
Why does M2.item(0, 0) return "#VALUE" ? What is the right way to compare two values of the same array / Range ?
 
     
    