EXCEL 2010找到最大值单元格并更改其颜色

时间:2014-03-10 15:56:37

标签: excel vba excel-vba excel-2010 cell

我正在研究VBA EXCEL 2010.

我需要在列中找到最大值并用颜色突出显示其单元格。

Sub findMax_1()
    Dim c As Range
    Dim max As Double
    Dim maxCell As String
     max = 0
     For Each c In Selection
        If c.Value > max Then
           max = c.Value
           maxCell = c.Address
        End If
     Next c
     ActiveSheet.Range("A10") = max
     ActiveSheet.Range(maxCell).Color = vbBlue
 End Sub

它不起作用。运行时错误438.

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

正如评论中提到的simco,您需要更改以下代码行:

ActiveSheet.Range(maxCell).Color = vbBlue

ActiveSheet.Range(maxCell).Interior.Color = vbBlue

您当前代码的问题在于,如果您没有选择任何内容,则最终会出现1004错误。克服这种情况的一种方法是提到simco来检查您是否选择了任何细胞。以下方法是我更喜欢的方法。假设您在A列中有数据:

enter image description here

使用以下代码:

Sub findMax_1()
    Dim c As Range
    Dim flag As Boolean
    Dim i As Integer

    Dim max As Double
    Dim maxCell As String
    flag = True
    i = 1
    max = 0
    While flag = True
        If Cells(i, 1) <> "" Then

            If Cells(i, 1) > max Then
               max = Cells(i, 1)
               maxCell = Range(Cells(i, 1), Cells(i, 1)).Address

            End If
              i = i + 1
        Else
            flag = False
        End If

    Wend
     ActiveSheet.Range("A10") = max
     ActiveSheet.Range(maxCell).Interior.Color = vbBlue
 End Sub

结果:

enter image description here

另外,您可以在我的博客上查看此文章,了解更多信息Excel VBA Formatting Cells and Range


同样,simco提到您可以使用条件格式,请选择包含数据的列:

enter image description here

从主页功能区选择 条件格式&gt;&gt;上/下规则&gt;&gt;前10项......&gt;&gt;

enter image description here

选择“1”从左侧文本框中,从右侧下拉列表中选择颜色:

enter image description here