修改一个循环

我有以下代码:

Case "END-BOX" EndBox = ActiveCell.Row Selection.Offset(-1, 2).Select Selection.ClearContents Rows(2).Insert Shift:=xlDown TotalCols = ActiveSheet.UsedRange.Columns.Count Col = 4 Cells(EndBox, Col).Select For i = EndBox To 1 Step -1 If Cells(i, Col).Value <> "" Then n = n + 1 Else Cells(i, Col).Value = n Cells(i, Col).Interior.ColorIndex = 4 n = 0 End If Next Range(EndBox).Select Selection.Offset(1, -2).Select 

这会导致在terminal框线上出现绿色单元,以及在新框线上出现绿色单元。 我只喜欢新的盒子颜色。 有什么办法来修改代码,以便它能做到这一点?

这是我的工作簿。

摆脱这样一句话:

Cells(i, Col).Interior.ColorIndex = 4

这是设置单元格颜色的线。

要仅对列B中的“新框”行进行着色,请将该行更改为:

If Cells(i, Col).Offset(0, -2).Value = "new-box" Then Cells(i, Col).Interior.ColorIndex = 4

注意:这不会撤消之前应用的颜色格式。

我会build议使用自动filter,而不是循环。 您正在检查列B中的“新框”,所以使用此代码。

 Dim lRow As Long Dim rng As Range With Sheets("Spare") '~~> Remove any filters .AutoFilterMode = False lRow = .Range("B" & .Rows.Count).End(xlUp).Row With .Range("B1:B" & lRow) 'Filter, offset(to exclude headers) .AutoFilter Field:=1, Criteria1:="NEW-BOX" Set rng = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow rng.Interior.ColorIndex = 4 End With '~~> Remove any filters ActiveSheet.AutoFilterMode = False End With