2016-12-02 29 views
0

我已經編寫了代碼來循環訪問特定值的範圍。如果該值等於「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 
+0

創建一個計數器v ariable和每次查找增加計數器1.當它達到您想要的數量(在這種情況下爲2)時,退出子 – tigeravatar

回答

2

如果您避免使用Select和其他親屬,而是使用引用ObjectsSheetsRange的IT更好。 此外,您還可以搜索的最後一排,在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
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 
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 
0

下面是一些另外的代碼:

 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