遍历代码并突出显示行。 只返回前两个发现

我已经编写了代码来遍历一个特定值的范围。 如果值等于“123”,则将整行绿色突出显示。 不过,我只想让它突出显示前两场比赛,并在那里停下来。 非常感谢。

Sub Macro3() Sheets("XYZ").Select Dim rng As Range Sheets("XYZ").Select Set rng = Range("L2:L10000") For Each cell In rng If cell.Value = "123" Then cell.EntireRow.Interior.ColorIndex = 4 End If Next End Sub 

最好避免使用Select和其他亲属,而使用引用的ObjectsSheetsRange s。 另外,您可以使用列L中的数据search最后一行,而不是循环遍历行10000。

 Option Explicit Sub Macro3() Dim Rng As Range, cell As Range Dim counter As Integer, LastRow As Long With Sheets("XYZ") ' find last row at Column "L" LastRow = .Cells(.Rows.Count, "L").End(xlUp).Row Set Rng = .Range("L2:L" & LastRow) For Each cell In Rng If cell.Value = "123" Then cell.EntireRow.Interior.ColorIndex = 4 counter = counter + 1 End If If counter >= 2 Then Exit For Next End With End Sub 
 Sub Macro3() Sheets("XYZ").Select Dim rng As Range dim count as integer 'Set the range in column D to loop through Sheets("XYZ").Select Set rng = Range("L2:L10000") For Each cell In rng If cell.Value = "123" Then cell.EntireRow.Interior.ColorIndex = 4 count = count + 1 End If if count >= 2 Then exit For Next End Sub 

过滤可以避免在单元格中循环

假设第1行有标题,你可以尝试:

 Dim cell As Range Dim counter As Integer With Sheets("XYZ") With .Range("L1", .Cells(.Rows.Count, "L").End(xlUp)) '<--| reference its column "L" cells from row 1 (header) down to last not empty row .AutoFilter field:=1, Criteria1:="123" '<--| filter referenced range on its first (and only) column with "123" If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then '<--| if any cell gets filtered For Each cell In .Resize(.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible) '<--| loop through filtered cells, skipping header cell.EntireRow.Interior.ColorIndex = 4 counter = counter + 1 '<--| update counter If counter = 2 Then Exit For '<--| exit at 2nd iteration Next cell End If End With .AutoFilterMode = False End With 

这里有一些额外的代码:

  Sub Macro3() Sheets("XYZ").Select Dim rng As Range greenrows = 0 Sheets("XYZ").Select Set rng = Range("b2:b10000") For Each cell In rng If cell.Value = "123" Then If greenrows = 2 Then Exit Sub cell.EntireRow.Interior.ColorIndex = 4 greenrows = greenrows + 1 End If Next End Sub