选择动态范围(行)并计算有色单元格-VBA

时间:2018-07-12 11:25:23

标签: vba access-vba

我有一张有彩色单元格的桌子。我需要通过VBA用户表单来计数表中的相关当前行。 我不确定如何为动态范围使用正确的语法。 这是我的代码:

我做错了什么?

Public Function UpdateTestCompletion()

Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Dim CurrentRange As Range
T_R = 1 'dynamic variable - set 1 just for test -mention the row count in the table starting from D_start cell
Set sht = Worksheets("Test_Data")
Set StartCell = Sheets("Test_Data").Range("D_Start").Offset(T_R, 8)
'Find Last Column
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column 
'the last raw of tests parameters
'Select Range
CurrentRange = sht.Range(StartCell, sht.Cells(StartCell.Row, LastColumn))

TotalGreen = CountColor(CurrentRange)
TComp_L.Caption = (TotalGreen / Sheets("T_list").Range("N14").Value) & " %"

End Function

以下是“ TotalGreen”功能的代码(也无效):

Function CountColor(range_data As Range) As Long
Dim datax As Range
Dim xcolor As Long
xcolor = RGB(169, 208, 142) 'green
For Each datax In range_data
   If datax.Interior.ColorIndex = xcolor Then
     CountColor = CountColor + 1
   End If
Next datax
End Function

请您帮助,谢谢

1 个答案:

答案 0 :(得分:1)

Range.Interior.ColorIndex是指Excel的内置Color值。使用Range.Interior.Color来指代RGB的颜色。

Function CountColor(range_data As Range, Optional xcolor As Long = -1) As Long
    Dim datax As Range
    Dim Count As Long
    If xcolor = -1 Then xcolor = RGB(169, 208, 142)   'green
    For Each datax In range_data
        If datax.Interior.Color = xcolor Then
            Count = Count + 1
        End If
    Next datax
    CountColor = Count
End Function

参考:Excel VBA color code list – ColorIndex, RGB color, VB color