修改循环

时间:2013-02-20 15:14:10

标签: excel excel-vba vba

我有以下代码:

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

它导致绿色单元格出现在端框线以及新框线上。我只想让新盒子的线条变色。有没有办法修改代码,以便它做到这一点?

Here是我的工作簿。

2 个答案:

答案 0 :(得分:1)

我建议使用Autofilter而不是循环。您正在检查Col B中的“New Box”,因此请使用此代码。

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

答案 1 :(得分:0)

摆脱说:

的界限

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

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

要仅为B列中带有“new-box”的行着色,请将该行更改为:

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

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

相关问题