Link to home
Start Free TrialLog in
Avatar of Genius123
Genius123Flag for United States of America

asked on

max value in vbscript

Hello,

I'm working vb script within Outlook.  I'm looking for the maximum value of multiple fields.  So for this:

msgbox Max(1,2,3,4)

I want 4.  The function Max doesn't exist though.

Thanks,
Joel
Avatar of Jeff Darling
Jeff Darling
Flag of United States of America image

If you pass as a string this function will work.

msgbox MAX("1,2,3,4")

Open in new window


Public Function MAX(sList)

arrList = Split(sList, ",")

For I = LBound(arrList) To UBound(arrList)
     If arrList(I) > numHighValue Then
          numHighValue = arrList(I)
     End If
Next

MAX = numHighValue

End Function

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Bill Prew
Bill Prew

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Genius123

ASKER

Ok, so I'm actually working with 4 date fields.  Also, how do you define sList?
Avatar of Bill Prew
Bill Prew

My approach will handle dates also.

Sub Test()
    v1 = 10
    v2 = 20
    v3 = 30
    v4 = 40
    MsgBox Max(Max(v1, v2), Max(v3, v4))
    v1 = CDate("1/1/2000")
    v2 = CDate("1/1/2010")
    v3 = CDate("1/1/2005")
    v4 = CDate("1/1/2004")
    MsgBox Max(Max(v1, v2), Max(v3, v4))
End Sub

Function Max(p1 As Variant, p2 As Variant) As Variant
    If p1 > p2 Then
        Max = p1
    Else
        Max = p2
    End If
End Function

Open in new window


»bp
go with bills solution

sample
dt1 = DateAdd("d", -3, Now())
dt2 = DateAdd("d", -1, Now())
dt3 = DateAdd("d", -4, Now())
dt4 = DateAdd("d", -2, Now())

Debug.Print dt1
Debug.Print dt2
Debug.Print dt3
Debug.Print dt4

Debug.Print "Highest!"
Debug.Print Max(Max(dt1, dt2), Max(dt3, dt4))

Open in new window

If you do want to go with passing all the values to the function in one shot, I would do an array, here's a comparison of the two approaches...

Sub Test()
    
    Dim a()
    
    v1 = 10
    v2 = 20
    v3 = 30
    v4 = 40
    MsgBox MaxPair(MaxPair(v1, v2), MaxPair(v3, v4))
    
    a = Array(v1, v2, v3, v4)
    MsgBox MaxArray(a())
    
    v1 = CDate("1/1/2000")
    v2 = CDate("1/1/2010")
    v3 = CDate("1/1/2005")
    v4 = CDate("1/1/2004")
    MsgBox MaxPair(MaxPair(v1, v2), MaxPair(v3, v4))

    a = Array(v1, v2, v3, v4)
    MsgBox MaxArray(a())

End Sub

Function MaxPair(p1 As Variant, p2 As Variant) As Variant
    If p1 > p2 Then
        MaxPair = p1
    Else
        MaxPair = p2
    End If
End Function

Public Function MaxArray(pArray() As Variant) As Variant
    For i = LBound(pArray) To UBound(pArray)
        If pArray(i) > MaxArray Then
              MaxArray = pArray(i)
        End If
    Next
End Function

Open in new window


»bp
thanks bill, that worked.