简体   繁体   English

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

[英]Selecting range of visible cells only with VBA

I have the following function "CountCcolor()" that I would like to use on a status tracker. 我要在状态跟踪器上使用以下函数“ CountCcolor()”。 My intention is to be able to use the function to find in a single columns range of visible cells how many are highlighted in a specific color, say green. 我的意图是能够使用该函数在可见列的单列范围内找到以特定颜色(例如绿色)突出显示的数量。

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

Thank you for your help in advance! 提前谢谢你的帮助!

Don't use Interior.ColorIndex 不要使用Interior.ColorIndex

Instead, just use Interior.Color . 相反,只需使用Interior.Color I was stumped by this once as well. 我也为此感到难过。 In short, the ColorIndex represents a palate of colors, not a unique color. 总之, ColorIndex代表的颜色的口感 ,而不是一个独特的色彩。 See here for more details 详情请看这里

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM