How do I find the highest value from a range of variables?

时间:2019-04-08 13:39:01

标签: excel vba variables

I am trying to find and display the highest value from a range of variables in VBA and only display the highest.

Sub Max_val()
    Dim Sh1 As String
    Dim Var(100) As Integer

    Book2 = ThisWorkbook.Name

    Sh1 = "Sheet1"

    Var(1) = Worksheets(Sh1).Cells(8, 6).Value
    Var(2) = Worksheets(Sh1).Cells(9, 6).Value
    Var(3) = Worksheets(Sh1).Cells(10, 6).Value
    Var(4) = Worksheets(Sh1).Cells(11, 6).Value
    Var(5) = Worksheets(Sh1).Cells(12, 6).Value

    'this is where I am trying to display the highest value'
    Worksheets(Sh1).Cells(28, 4).Value = Var(1)
End Sub

Any help would be greatly appreciated, many thanks.

1 个答案:

答案 0 :(得分:2)

Use Application.Max to return the max of the array.

You can also mass load the array. Change the array to a Variant and load the entire range as one.

Sub Max_val()

    Dim Sh1 As Worksheet
    Dim Var As Variant

    Set Sh1 = ThisWorkbook.Worksheets("Sheet1")

    With Sh1
        Var = .Range(.Cells(8, 6), .Cells(107, 6)).Value
        .Cells(28, 4).Value = Application.Max(Var)
    End With

End Sub