Excel VBA - 列所需的循环

时间:2014-01-31 21:13:52

标签: excel vba excel-vba excel-2010

我很擅长VBA,我无法弄清楚如何让它发挥作用。我有一个列(列K),在K1中有一个标题。我每天都会收到此电子表格,但它的行数不同。列K的数字为0-100。我需要根据K列中的值突出显示某些行的某些颜色。这是我到目前为止所做的,但它一直向下,使每一列都是红色字体。我需要它通过k2循环到最后一个带有值的K单元格并更改每行的字体颜色。

Columns("K").Select
Dim firstCell As Integer
Dim finalCell As Integer
firstCell = Range("K2")
finalCell = Range("K65536").End(xlUp).Row
For i = firstCell To finalCell

If i > 5 Then
    Rows(i).Select
    With Selection.Font
        .Color = RGB(255, 0, 0)
    End With
ElseIf i = 4 Then
    Rows(i).Select
    With Selection.Font
        .Color = RGB(226, 107, 10)
    End With
ElseIf i = 3 Then
    Rows(i).Select
    With Selection.Font
        .Color = RGB(0, 176, 80)
    End With
ElseIf i = 2 Then
    Rows(i).Select
    With Selection.Font
        .Color = RGB(0, 112, 192)
    End With
ElseIf i = 1 Then
    Rows(i).Select
    With Selection.Font
        .Color = RGB(112, 48, 160)
    End With
End If
Next i

2 个答案:

答案 0 :(得分:3)

在你的if语句中,你只是引用i,而不是你想要的列K和行i中包含的值。

所以改变if语句:

If i > 5 Then
'and
ElseIf i = 4 Then

为:

If Range("K" & i).Value > 5 Then
'and
ElseIf Range("K" & i).Value = 4 Then

对于你所有的if语句。还要更改第一个和最后一个单元格语句。他们可能会工作,但我知道这些会:

finalCell = ActiveSheet.Range("K" & ActiveSheet.Rows.Count).End(xlUp).Row
'and 
firstCell = 2

答案 1 :(得分:1)

由于我在评论中提到的两个链接没有涉及自动过滤器,请参阅此示例。如果数字是5怎么办?您的代码无法处理。你有没有意味着“> 4”?如果是,请在下面的代码中将“> 5”更改为“> 4”。

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long, i As Long
    Dim rng As Range

    '~~> Change this to the relevant sheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        '~~> Remove any filters
        .AutoFilterMode = False

        lRow = .Range("K" & .Rows.Count).End(xlUp).Row

        With .Range("K1:K" & lRow)
            For i = 1 To 4
                .AutoFilter Field:=1, Criteria1:="=" & i

                Set rng = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow

                If Not rng Is Nothing Then
                    Select Case i
                        Case 1: rng.Font.Color = RGB(112, 48, 160)
                        Case 2: rng.Font.Color = RGB(0, 112, 192)
                        Case 3: rng.Font.Color = RGB(0, 176, 80)
                        Case 4: rng.Font.Color = RGB(226, 107, 10)
                    End Select

                    Set rng = Nothing
                End If

                ws.AutoFilter.ShowAllData
            Next i

            .AutoFilter Field:=1, Criteria1:=">5" '<~~ OR "<4" ???
            Set rng = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
            If Not rng Is Nothing Then rng.Font.Color = RGB(255, 0, 0)
        End With

        '~~> Remove any filters
        .AutoFilterMode = False
    End With
End Sub