VBA,查找最小值,根据该值突出显示行

时间:2019-01-07 17:57:47

标签: excel vba

我有一个值范围,我想找到MIN,然后突出显示此Min值所在的行。

KEY: catt: VALUE: zeus
KEY: catt: VALUE: xena

如何根据可变的最坏情况突出显示行? 我有静态范围,找到最小值,但是现在我需要突出显示最坏情况变量的行。

3 个答案:

答案 0 :(得分:1)

您可以这样做。

但是如果您反复设置最小值,将无法正常工作。

此外,您可以使用条件格式并避免使用VBA。

Sub worstcase()

Dim Rng As Range, worstcase, i As Long

Set Rng = Range("H44:H54")

With Rng
    worstcase = Application.WorksheetFunction.Min(.Cells)
    i = Application.Match(worstcase, .Cells, 0)
    .Cells(i).EntireRow.Interior.Color = vbRed
End With

End Sub

答案 1 :(得分:1)

具有发现条件的突出显示行

代码突出显示找到最小值的每一行。使用“退出用于”仅突出显示第一个。

代码

Sub worstcase()

    Dim worstcase As Double ' Long for whole numbers.
    Dim rng As Range
    Dim cell As Range

    With Worksheets("Sheet1")
        Set rng = .Range("H44:H54")
        worstcase = Application.WorksheetFunction.Min(rng)
        Debug.Print worstcase

        For Each cell In rng
            If cell.Value = worstcase Then
                cell.EntireRow.Interior.ColorIndex = 3 ' Hightlight whole row.
                'cell.Interior.ColorIndex = 5 ' Hightlight only cell.
                'Exit For ' To highlight only the first found row.
            End If
        Next

    End With

End Sub

编辑:

Sub worstcase()

    Const cFirst As Variant = "H"
    Const cLast As Variant = "Q"

    Dim worstcase As Double ' Long for whole numbers.
    Dim rng As Range
    Dim cell As Range

    With Worksheets("Sheet1")
        Set rng = .Range("H44:H54")
        worstcase = Application.WorksheetFunction.Min(rng)
        Debug.Print worstcase

        For Each cell In rng
            If cell.Value = worstcase Then
                .Range(.Cells(cell.Row, cFirst), .Cells(cell.Row, cLast)) _
                    .Interior.ColorIndex = 3 ' Hightlight cells.
                'Exit For ' To highlight only the first found cells.
            End If
        Next

    End With

End Sub

答案 2 :(得分:1)

根据以下公式创建条件格式设置规则。

=$H44=min($H$44:$H$54)

此VBA将为第44:54行创建CFR。

With worksheets("sheet1").range("44:54")
    .FormatConditions.Delete
    .FormatConditions.Add Type:=xlExpression, Formula1:="=$H44=min($H$44:$H$54)"
    .FormatConditions(.FormatConditions.Count).Interior.Color = vbred
End With