Excel VBA – 循环需要一列

我很擅长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 

在你的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 

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

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

由于我在评论中提到的两个链接不包括有关自动filter,请参阅此示例。 另外如果数字是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