2016-12-02 5 views
0

特定の値の範囲をループするコードを記述しました。値が "123"に等しい場合は、行全体をハイライトします。しかし、私はそれが見つけた最初の2つの試合をハイライトし、そこで停止したいだけです。どうもありがとう。コードをループし、行を強調表示します。最初の2つのファインだけを返します

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 Sを使用しています。また 、あなただけの行をループするのではなく、列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 
関連する問題