2016-01-06 59 views
1

我认为我的ForIFNext语句的顺序有问题,我试图只突出显示满足所有条件的行,相反,当我的代码使其突出显示的部分所有行都单独突出显示,代码似乎运行速度很慢,我相信我执行了太多迭代?迭代次数过多:仅在满足所有条件后突出显示单元行所需的语法

Sub SWAPS100() 

Dim rng As Range, lCount As Long, LastRow As Long 
Dim cell As Object 

Sheets("Output").Activate 

With ActiveSheet 

    LastRow = .Cells(Rows.Count, 1).End(xlUp).Row 

    For Each cell In .Range("E2:E" & LastRow) 'new position 
     If cell = "N" Then 
     Debug.Print 
          For Each cell1 In .Range("U2:U" & LastRow) 'Secuirty type 
           If cell1 = "SW" Then 
            For Each cell2 In .Range("J2:J" & LastRow) 'prior px 
             If cell2 = 100 Then 
              For Each cell3 In .Range("I2:I" & LastRow) 'current px 
                If cell3 <> 100 Then 

      'With cell.Interior 
     With cell.EntireRow.Interior 
     .Pattern = xlSolid 
     .PatternColorIndex = xlAutomatic 
     .Color = 6382079 
     .TintAndShade = 0 
     .PatternTintAndShade = 0 
     End With 
                  End If 
                 Next cell3 
                 End If 
                Next cell2 
                End If 
               Next cell1 
               End If 
              Next cell 


End With 
+0

为什么不使用[AND](http://stackoverflow.com/questions/9140318/how-to-use-and-in-if-statement-vba)?除非满足所有条件,否则你似乎没有做任何事情。 – Raystafarian

回答

2

由于@Raystafarian评论,因为我打字,在使用And你如果statment,而不是所有的循环:

Sub SWAPS100() 

Dim rng As Range, lCount As Long, LastRow As Long 
Dim cell As Object 

Sheets("Output").Activate 

With ActiveSheet 

    LastRow = .Cells(Rows.Count, 1).End(xlUp).Row 

    For Each cell In .Range("E2:E" & LastRow) 'new position 
     If cell = "N" And cell.Offset(, 16) = "SW" And cell.Offset(, 5) = 100 _ 
      And cell.Offset(, 4) = 100 Then 
      With cell.EntireRow.Interior 
       .Pattern = xlSolid 
       .PatternColorIndex = xlAutomatic 
       .Color = 6382079 
       .TintAndShade = 0 
       .PatternTintAndShade = 0 
      End With 
     End If 
    Next cell 


End With 

配备了可单独循环的每一行会走缓,并很可能会一直辩解。只要你在每个列中有一个单元格来证明if语句的正确性,那么它将着色所有行。

而且这可以用条件格式来完成以下公式:

=AND($E2="N",$U2="SW",$J2=100,$I2=100) 
2

虽然上述Conditional Formatting与本机工作表公式是“上即时”更新更好的解决方案,一系列的应用于列的AutoFilter methods比任何涉及循环单元格的过程要快得多。

Sub SWAPS100() 

    Application.ScreenUpdating = False 
    With Sheets("Output") 
     If .AutoFilterMode Then .AutoFilterMode = False 
     With .Cells(1, 1).CurrentRegion 
      .AutoFilter Field:=5, Criteria1:="N" 
      .AutoFilter Field:=9, Criteria1:=100 
      .AutoFilter Field:=10, Criteria1:=100 
      .AutoFilter Field:=21, Criteria1:="SW" 
      With .Resize(.Rows.Count - 1, 1).Offset(1, 4) 
       If CBool(Application.Subtotal(103, .Cells)) Then 
        .Cells.EntireRow.Interior.Color = 6382079 
       End If 
      End With 
     End With 
     If .AutoFilterMode Then .AutoFilterMode = False 
    End With 
    Application.ScreenUpdating = True 

End Sub 
相关问题