如果相邻单元符合标准,则根据颜色计算单元格

对于VBA技能比我更熟练的人来说,这个问题可能非常容易。 我的问题是,我想要计算包含特定颜色的单元格,但只有在符合相邻单元格中的条件的情况下。 我已经发现如何做到这一点,如果我只想计算基于颜色,这就是它的样子:

Function CountCcolor(range_data As Range, criteria As Range) As Long Dim datax As Range Dim xcolor As Long 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 

所以在我的例子中,现在我要计算单元格列B的颜色为绿色,如果相邻单元格列A等于苹果。 示例图像

你可以帮我吗? 我有点卡在这里! 谢谢你,大家快乐!

只要在你的If语句中添加另一个条件

 If datax.Interior.ColorIndex = xcolor And LCase(datax.Offset(0,-1).Value) = "apple" Then 

我用LCase获得Appleapple

当然,当你使用Offset为负值时,你必须确保你不会将它应用到靠近表单最后的单元格(在这里是第一列),否则你会得到一个错误。

如果你想要的单元格在datax的同一行,但列A ,只需使用datax.Row获取行号:

 yoursheet.Cells(datax.Row, 1).Value 

其中yoursheet是您正在处理的工作区(例如data_range.Sheet )。 你可以用"A"replace列索引(如果你喜欢的话)(我更喜欢使用数字)。

这里有更多的方法来获取单元格在同一行和第一列:

 datax(, 2 - datax.Column) ' no auto-complete datax.Offset(, 1 - datax.Column) ' auto-complete datax.EntireRow.Cells(1) ' no auto-complete datax.EntireRow.Resize(, 1) ' auto-complete