如何使用此流程图创建宏?

时间:2013-02-17 07:55:29

标签: vba

您能否帮助我获取vba代码以突出显示此列的最小值和最大值?

例如:

   Col A   | Col B
   --------+---------
   Store 1 |   500
   Store 2 |   400
   Store 3 |   300
   ========+=========
   Total   |  1200

1 个答案:

答案 0 :(得分:0)

我完全同意@Peter L评论条件格式使用MIN& MAX将顺利完成工作, 但如果你真的想要VBA代码,这种方法可以完成这项工作

Sub HighlightMinMax()
 Const column As Integer = 2
 Dim row As Integer, minRow As Integer, maxRow As Integer
 Dim minValue, maxValue
 ' initialize variables
 row = 1
 minRow = 1
 maxRow = 1
 minValue = Cells(row, column)
 maxValue = Cells(row, column)
 ' loop until found "Total" in the first column
 While Cells(row, 1) <> "Total"
    Debug.Print Cells(row, 1) ' inspect the label
    If (Cells(row, column) < minValue) Then
        minRow = row
        minValue = Cells(row, column)
    End If
    If (Cells(row, column) > maxValue) Then
        maxRow = row
        maxValue = Cells(row, column)
    End If
    row = row + 1
 Wend
 ' select the cell with the min value and highlight it ...changing the background color to green
 Cells(minRow, column).Select
 With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 5296274
        .TintAndShade = 0
        .PatternTintAndShade = 0
 End With
 ' select the cell with the max value and highlight it ...changing the background color to red
 Cells(minRow, column).Select
 With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 5296274
        .TintAndShade = 0
        .PatternTintAndShade = 0
 End With
 Cells(maxRow, column).Select
 With Selection.Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .Color = 255
    .TintAndShade = 0
    .PatternTintAndShade = 0
 End With
End Sub