In Excel I can write a formula like =Max(1,2,3). It correctly gives me 3 as the result.
In Access I can use Max in a totals query to find the highest value of a field across all the rows in a table.
But what if I want the highest value across three fields in a single row, or of three variabls in VBA. I can't use Max in that scenario in Access. Here's a user defined function that will work in both those scenarios:
Public Function GreatestValue(ParamArray varValues() As Variant) As Variant Dim varMax As Variant Dim lngCounter As Long varMax = Null For lngCounter = LBound(varValues) To UBound(varValues) If IsNull(varMax) Then varMax = varValues(lngCounter) Else If varValues(lngCounter) > varMax Then varMax = varValues(lngCounter) End If End If Next lngCounter GreatestValue = varMax End Function
SELECT [A],[B],[C],GreatestValue([A],[B],[C]) AS HighestField FROM MyTableor in VBA:
MyResult=GreatestValue(MyFirstNumber,MySecondNumber)
It should work with any number of values and with numbers or strings.
4 comments:
Thanks. I had seen the code on the microsoft site, but that only works if the first field doesn't have null values. Your code avoids that problem.
Great work! Is there a way to also find the next highest value?
Thank you very much1 this help me a lot to calculate the maximum number of days.
www.room4pano.com
You rock!!! This thing works with dates - I used it for an Access 2007 form, and it calc'd the dates using four field names! Thanks!
Post a Comment