VBA Example - Find The Maximum Or Minimum Value

Suppose you have a sales data for four regions, and you want to know the region with the highest sales. See the data below.



The VBA code is this:

Sub find_max()
    Dim row As Integer
    Dim max As Single
    max = 0
    Dim sale As Single
    For row = 2 To 5
        sale = Cells(row, 2)
        If sale > max Then
            max = sale
        End If
    Next
    Cells(6, 2) = max
    MsgBox ("done")
End Sub


By running the code, you get the maximum value:



If you want to find the minimum value instead of the maximum value, the code is very similar.

Sub find_min()
    Dim row As Integer
    Dim min As Single
    min = 10000 'select a very large value
    Dim sale As Single
    For row = 2 To 5
        sale = Cells(row, 2)
        If sale < min Then
            min = sale
        End If
    Next
    Cells(6, 2) = min
    MsgBox ("done")
End Sub

Comments

Popular posts from this blog

Excel - IF function

Excel - VLOOKUP function

Excel - Hierarchical chart (Treemap)