能否請您做一個調試打印這個來看看小區colourIndex真的3
Debug.Print Cell.Interior.ColorIndex
,因爲
Cell.Interior.Color
需要RGB
匹配......在那裏,你只需要.ColorIndex
匹配;)非常精確Color
支持更多,當ColorIndex
支持有限數量的顏色。但最有可能你的情況3
不是red
您嘗試匹配的顏色..
所以它必須是,
IF Cell.Interior.ColorIndex <> 3 then
//count count
End if
我嘗試了你的子:有幾個問題。我已經把代碼放在旁邊了。請嘗試以下出。
- 請使用
Explicit reference for Ranges e.g.
表(1).Range it helps alot. So changed the way
上次使用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
輸出:
@馬特請你試試這個.. 。因爲我碰巧做了一些[顏色指數](http://stackoverflow.com/questions/14198098/excel-vba-apply-auto-filter-and-sort-by-specific-colour/14200175#comment19690275_14200175)昨天..如果沒有錯我不能使用'.color' .. – bonCodigo
我將代碼更改爲.ColorIndex。變化什麼都不做。一個調試語句給出的值爲1.單元格顏色將爲「null」,「黑色」,「紅色」或「橙色」 – matt
@matt我運行了你的代碼,請看看修訂後的版本和證明;) – bonCodigo