仅使用VBA选择可见单元格的范围

时间:2018-10-04 02:28:19

标签: vba range excel-2010 cell visible

我想在状态跟踪器上使用以下函数“ CountCcolor()”。我的意图是能够使用该函数在可见列的单列范围内找到以特定颜色(例如绿色)突出显示的数量。

Function CountCcolor(range_data As Range, criteria As Range) As Long

    Dim datax As Range
    Dim xcolor As Long

    ' The next one-liner does not work. Without it, it selects visible and hidden cells. I only want it to select visible cells:
    range_data = Selection.SpecialCells(xlCellTypeVisible).Select

    xcolor = criteria.Interior.ColorIndex
    For Each datax In range_data
        If datax.Interior.ColorIndex = xcolor Then
             CountCcolor = CountCcolor + 1
        End If
    Next datax
End Function

谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

请勿使用Interior.ColorIndex

相反,只需使用Interior.Color。我也为此感到难过。简而言之,ColorIndex代表颜色的上颚,而不是唯一的颜色。有关更多详细信息,请参见here

Function CountCcolor(range_data As Range, criteria as Range) As Long

Dim myRange As Range, myCell As Range, TempCount As Long
Set myRange = range_data.SpecialCells(xlCellTypeVisible)

For Each myCell In myRange
    If myCell.Interior.Color = criteria.Interior.Color Then
        TempCount = TempCount + 1
    End If
Next myCell

CountCcolor = TempCount

End Function