您能否对此进行调试打印,以查看单元格 colourIndex 是否真的3
Debug.Print Cell.Interior.ColorIndex
因为,
Cell.Interior.Color
需要 aRGB
来匹配...你只需要.ColorIndex
匹配 ;) 非常准确地说,当支持有限数量的颜色Color
时支持更多。ColorIndex
但在您的情况下,最有可能3
不是red
您要匹配的颜色。
所以它必须是,
IF Cell.Interior.ColorIndex <> 3 then
//count count
End if
我试过你的潜艇:有几个问题。我在代码旁边放了注释。请尝试以下方法。
- 请使用
Explicit reference for Ranges e.g.
Sheets(1).Range it helps alot. So changed the way
Last Used Row` 被发现。
- 您没有设置
colorD
它,它只有 2 行。于是改成,
Set colorD = Sheets(2).Range("D2").Resize(endRow)
If
正在做相反的事情<>
,所以将其更改为 If Cell.Interior.ColorIndex = 3 Then
- 一个错字将其更改为
M = M - redM
修改后的代码:
Option Explicit
Sub countbyColourAndGender()
Dim endRow As Long
Dim redF As Long
Dim redM As Long
Dim F As Long
Dim M As Long
Dim colorD As Range
Dim Cell As Range
Dim cellVal As String
'Find the ending row --HERE: it gave an error, so changed it..
endRow = Sheets(2).Cells(Sheets(2).Rows.Count, "C").End(xlUp).Row
'Ensure ending row is at least Row 2
If endRow < 2 Then
endRow = 2
End If
'Count all the Females
F = Application.WorksheetFunction.CountIf(Sheets(2).Range("C2:C" & endRow), "F")
'Count all the Males
M = Application.WorksheetFunction.CountIf(Sheets(2).Range("C2:C" & endRow), "M")
'Set the applicable Column D range -- HERE: changed using `Resize`
Set colorD = Sheets(2).Range("D2").Resize(endRow)
'Loop through each cell in Column D
For Each Cell In colorD
If Cell.Interior.ColorIndex = 3 Then '-- HERE: not <> but =
'Red Cell found, get the cell value from Column C
cellVal = LCase(Cell.Offset(-1, -1).Value)
If cellVal = "f" Then redF = redF + 1 'Increment count of red Females
If cellVal = "m" Then redM = redM + 1 'Increment count of red Males
End If
Next Cell
'Subtract any red Females
F = F - redF
'Subtract any red Males : HERE it has to subsctract not equal..
M = M - redM
'Alert User with counts
MsgBox ("Females=" & F & "," & "Males=" & M)
End Sub
输出: