如何在可见范围内查找单元格值

时间:2016-07-19 23:56:05

标签: excel vba

我有很长的条目列表可以很快地完成,其中一列F列经常发生变化。由于我将单独浏览每个条目,因此我想突出显示整列红色,其中列F中的值发生变化,以便于查看。这是我到目前为止所写的内容:

Dim visRng As Range, rngTop As Long, rngBot As Long
rngTop = ActiveWindow.visiblerange.Row
rngBot = ActiveWindow.visiblerange.Row + ActiveWindow.visiblerange.Rows.Count - 2
visRng = Worksheets("Work").Range("F" & rngTop, "F" & rngBot)

    For Each Cell In visRng
        If Cell.Value = Cell.Offset(-1).Value _
            And Cell.Interior.ColorIndex = 0 Then
            Cell.EntireRow.Interior.ColorIndex = 3
        End If
    Next

我在定义“visRng”的行上一直出错:

  

运行时错误'91':   对象变量或未设置块变量

我对VBA很新,并且自学成才,所以我不能保证我会理解所有的行话。非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

请参阅评论以获得解释。

Sub FindAndColor()

    Dim visRng As Range
    Dim rngCell As Range


    '/ Set to range object. Yiu can't simply asign to it.
    '/ This will get rid of Error 91
    '/ Just Use VisibleCells of the usedRange
    Set visRng = Worksheets("Work").UsedRange.SpecialCells(XlCellType.xlCellTypeVisible)

    '/ Loop through the range
    For Each rngCell In visRng.Cells
        If rngCell.Row <> 1 Then
        If rngCell.Value = rngCell.Offset(-1).Value _
        And rngCell.Interior.ColorIndex = -4142 Then    '/ -4142 is the default interior colorindex
            rngCell.EntireRow.Interior.ColorIndex = 3
        End If
        End If
    Next

End Sub