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

时间:2016-12-02 17:24:17

标签: excel vba excel-vba

我编写了代码来遍历特定值的范围。如果该值等于" 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

3 个答案:

答案 0 :(得分:2)

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 :(得分:2)

如果您避免使用Select和其他亲属,而是使用引用的ObjectsSheetsRange,则会更好。 此外,您可以使用列L中的数据搜索最后一行,而不是仅循环遍历行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

答案 2 :(得分:0)

过滤可以避免循环遍历单元格

假设第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