I needed to find the max and min deviation from zero, irrespective of the sign. However, I found no way to do that using standard Excel functions when both positive and negative numbers are involved. So, I created my own VBA functions (based on code I found elsewhere) that works every time, even when some of the values are null or strings (non-numeric).
Here are the two functions MAX_ABS(range) and MIN_ABS(range, [optional boolean] allowZeros)
MAX_ABS is simple and straightforward:
Function MAX_ABS(SelectRng As Range) As Double
Dim result As Double
Dim work As Double
result = 0
myarray = SelectRng.Value
For i = 1 To UBound(myarray, 1)
For j = 1 To UBound(myarray, 2)
If IsNumeric(myarray(i, j)) = True Then 'Numbers Only
work = VBA.Abs(myarray(i, j))
If work > VBA.Abs(result) Then 'Test
result = myarray(i, j) 'Save new max
End If
End If
Next
Next
MAX_ABS = result
End Function
MIN_ABS is a bit trickier because if you initialize the return value to zero then it will always return zero, so you need to work around that. So I use an optional boolean parameter to allow zeros or ignore them.
Function MIN_ABS(SelectRng As Range, Optional allowZeros As Boolean = False) As Double
Dim work As Double
Dim result As Double
Dim firstHit As Boolean
result = 0
firstHit = True
myarray = SelectRng.Value
For i = 1 To UBound(myarray, 1)
For j = 1 To UBound(myarray, 2)
If IsNumeric(myarray(i, j)) = True Then 'Numbers Only
work = VBA.Abs(myarray(i, j))
'Zeros allowed
If allowZeros = True Then
If firstHit = True Then 'First pass -- Initialize
firstHit = False
result = myarray(i, j) 'Save first value
ElseIf work < VBA.Abs(result) Then 'Subsequent pass -- Test
result = myarray(i, j) 'Save new min
End If
If work = 0 Then
GoTo getout 'Zero -- no reason for further tests
End If
'Zeros not allowed
ElseIf result = 0 And work > 0 Then 'First pass -- Initialize
result = myarray(i, j)
ElseIf work > 0 And work < VBA.Abs(result) Then 'Subsequent pass -- Test
result = myarray(i, j)
End If
End If
Next
Next
getout:
MIN_ABS = result
End Function
Here are the results of the functions on a list of values that includes numbers, strings, and blanks.
Results of MAX_ABS and MIN_ABS