I'm completely new to VBA and have decided to try recreate excels built in functions. I'm currently trying to create a function that finds the median. for example, it first identifies whether the array is column vector or row vector. i used bubble sort to sort my array in ascending order and then apply a code to find the median value of the sorted array.
However i seem to get a error during the sort, it exists when it tries to swap two values. i get #VALUE error.
Function mymedian(x As Range) As Double
' order array of values asc
' use bubblesort
Dim nr As Integer
Dim nc As Integer
Dim i As Integer
Dim j As Integer
Dim temp As Double
Dim n As Integer
nr = x.Rows.count
nc = x.Columns.count
' col vector
If nc = 1 Then
For i = 2 To nr
For j = 2 To nr
If x.Cells(j - 1, 1).Value > x.Cells(j, 1).Value Then
temp = x.Cells(j, 1)
x.Cells(j, 1).Value = x.Cells(j - 1, 1).Value ' code exists here
x.Cells(j - 1, 1) = temp
n = n + 1
End If
Next j
Next i
Else
' row vector
If nc > 1 Then
For i = 2 To nc
For j = 2 To nc
If x.Cells(1, j - 1).Value > x.Cells(1, j).Value Then
temp = x.Cells(1, j)
x.Cells(1, j) = x.Cells(1, j - 1).Value
x.Cells(1, j - 1) = temp
n = n + 1
End If
Next j
Next i
End If
End If
As a sub this works fine, does this imply bubble sorts only work as sub routines? i also tried to call the sub within a function, however this wasn't working.
Sub bubblesort()
Dim x As Range
Set x = Selection
Dim nr As Integer
Dim temp As Double
Dim i As Integer
Dim j As Integer
nr = x.Rows.count
For i = 2 To nr
For j = 2 To nr
If x.Cells(j - 1, 1).Value > x.Cells(j, 1).Value Then
temp = x.Cells(j, 1)
x.Cells(j, 1) = x.Cells(j - 1, 1)
x.Cells(j - 1, 1) = temp
End If
Next j
Next i
End Sub
Function middle(x As Range)
Dim n As Integer
Dim mid As Double
Call bubblesort(x)
n = x.Rows.count
mid = x.Cells(n / 2, 1).Value
middle = mid
End Function