迭代次数过多:只有满足所有条件后才需要突出显示单元格行的语法

我想我的IFNext语句的顺序有问题,我试图只突出显示所有条件符合的行,而当我的代码使其突出显示部分所有行都单独突出显示,代码似乎运行相当慢,我相信我执行太多的迭代?

 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 

作为@Raystafarian评论,因为我打字,使用And你的if语句,而不是所有的循环:

 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 

循环每行单独它会变得缓慢,最有可能总是certificate。 只要你在每个列中有一个单元格来validationif语句,那么它就会为所有行着色。

也可以通过下面的公式使用条件格式来完成:

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

虽然前面提到的使用本地工作表公式的上述条件格式是“实时”更新的更好解决scheme,但应用于列的一系列AutoFilter方法将比包含循环遍历单元的任何过程快得多。

 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