Search code examples
excelvbamedian

Finding the median without using the function


I'm trying to find the median without using the function.

Dim i As Integer
Dim passNum As Integer
Dim temp As Integer
Dim aantal As Integer
Dim n(1 To 50) As Single
Dim p As Integer
Dim j As Single
Dim t As Single
Dim median As Single

aantal = InputBox("how many n variables do you want max 50")

For p = 1 To aantal
    n(p) = InputBox("geef " & aantal & " nummers")
Next

'Rem bubble sort names
For passNum = 1 To aantal - 1
    For i = 1 To aantal - passNum
        If n(i) < n(i + 1) Then
            temp = n(i)
            n(i) = n(i + 1)
            n(i + 1) = temp
        End If
    Next i
Next passNum

'Rem display alphabetized list
For i = 1 To aantal
    Worksheets(1).Cells(i, 1) = n(i)
Next i

'find the median
t = aantal Mod 2

If t > 0 Then
    median = n(aantal + 1) / 2
Else
    median = (n(aantal / 2) + (n(aatnal) / 2) + 1) / 2
End If

Worksheets(1).Cells(1, 2) = median

End Sub

This won't find the median.

I tried changing n(aantal) for something else. That either gives me the wrong number or nothing.


Solution

  • Maybe try this:

    Sub Median()
    
        Dim i As Integer
        Dim aantal As Integer, tmp as double
        ReDim n(0) As Double
    
    100:        
        aantal = InputBox("how many n variables do you want max 50")
        If aantal > 50 Then Goto 100
        
        ReDim n(aantal - 1)
        For i = 0 To UBound(n)
            n(i) = CDbl(InputBox("Geef nr " & i + 1 & " van " & aantal & " nummers"))
        Next
        
        For i = LBound(n) To UBound(n)
            For j = i + 1 To UBound(n)            
                If n(i) > n(j) Then
                    tmp = n(j)
                    n(j) = n(i)
                    n(i) = tmp
                End If
            Next
        Next
        
        m = aantal Mod 2
        ix = ((aantal + m) / 2) - 1
        If (m = 1) Then
            nMedian = n(ix)
        Else
            nMedian = (n(ix) + n(ix + 1)) / 2
        End If
        
        Debug.Print nMedian        
        
    End Sub