简体   繁体   English

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

[英]Select Dynamic Range (rows) and count colored cells - VBA

I have a table with colored cells.我有一张带有彩色单元格的表格。 I need, through VBA User form, to count the relevant current row in the table.我需要通过 VBA 用户表单来计算表中的相关当前行。 I'm not sure how to use the right syntax for dynamic range.我不确定如何为动态范围使用正确的语法。 Here is my code:这是我的代码:

What i'm doing wrong?我在做什么错?

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

Here is the code of 'TotalGreen' function (also doesn't work):这是“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

Please your help, thanks请你的帮助,谢谢

Range.Interior.ColorIndex refers to Excel's built in Color values. Range.Interior.ColorIndex指的是 Excel 的内置颜色值。 Use Range.Interior.Color to refer to RGB colors.使用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

Reference: Excel VBA color code list – ColorIndex, RGB color, VB color参考: Excel VBA 颜色代码列表——ColorIndex、RGB 颜色、VB 颜色

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

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