Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch the maximum value from an array

Tags:

excel

vba

I have an array that looks like this:

Dim values(1 To 3) As String

values(1) = Sheets("risk_cat_2").Cells(4, 6).Value
values(2) = Sheets("risk_cat_2").Cells(5, 6).Value
values(3) = Sheets("risk_cat_2").Cells(6, 6).Value

What I would like to do now is get the maximum value from all the values in string. Is there an easy way in VBA to fetch the max value from an array?

like image 665
Frits Verstraten Avatar asked Jun 13 '16 12:06

Frits Verstraten


2 Answers

Is there an easy way in VBA to fetch the max value from an array?

Yes - if the values are numeric. You can use WorksheetFunction.Max in VBA.

For strings - this won't work.

Sub Test2()
    Dim arr(1 To 3) As Long

    arr(1) = 100
    arr(2) = 200
    arr(3) = 300

    Debug.Print WorksheetFunction.Max(arr)

End Sub
like image 81
Robin Mackenzie Avatar answered Sep 22 '22 21:09

Robin Mackenzie


Simple loop would do the trick

Dim Count As Integer, maxVal As Long
maxVal = Values(1)
For Count = 2 to UBound(values)
    If Values(Count) > maxVal Then
        maxVal = Values(Count)
    End If
Next Count
like image 32
RGA Avatar answered Sep 25 '22 21:09

RGA