[英]If cell is highlight then
我有一個表格,我想計算一行中突出顯示的單元格數量?
我試過尋找一個公式。 我嘗試針對彩色單元格獲取 COUNT-IF。
我猜你需要某種 VBA 代碼,因為沒有公式(否則我不會在這里)
任何選項來獲取突出顯示的單元格計數?
我不認為有像 vlookup、sum、countif 等直接的公式。 所以不幸的是它需要一個宏。
創建一個宏,這是我使用的代碼:
Sub COUNT_HIGHLIGHTS()
'
' COUNT_HIGHLIGHTS
'
'Defining variables
Dim LastRow As Long, Count As Integer
'Getting a number value for the number of rows in the table (as this can vary on table size)
LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
'For loop to loop through rows
For i = 2 To LastRow
'Count is the number of cells in the row which are highlighted
Count = 0
'For loop for cells within the row (My table always has 36 cells)
For j = 5 To 36
'If statement to check if cell is highlighted
If Cells(i, j).Interior.Color = 65535 Then
'Add +1 to count ever time a highlighted cell is found
Count = Count + 1
End If
Next j
'find cell at the end of the row and add the count
Cells(i, 37).Select
Selection.Value = Count
Next i
End Sub
完成后,您會在最后獲得一列
第 1 列 | 第 2 欄 | 第 3 欄 | ...... 表格外的列 ColValue 1 | ColValue2| ColValue3| ....... 5(如果表中的 5 個單元格高亮顯示)
然后只需將表過濾到您創建的計數值,除 0 之外的所有內容
希望這有幫助
您可能喜歡為此使用 UDF(用戶定義函數)。 這是一個。 它將計算所有並非沒有顏色的單元格,無論它們具有哪種顏色。
Function HighLightCount(Target As Range) As Integer
' 14 Feb 2018
Dim Cell As Range
Dim Fun As Integer
For Each Cell In Target
Fun = Fun - Int(Cell.Interior.Color <> 16777215)
Next Cell
HighLightCount = Fun
End Function
將代碼安裝在標准代碼模塊中(默認情況下,在您更改名稱之前,它將是Module1
)。 像普通 Excel 函數一樣從工作表中調用該函數,例如,
=HighLightCount(A2:J2)
您可以像其他任何單元格一樣將公式復制/粘貼到其他單元格。 您還可以將其嵌入到 Excel 的內置函數中,例如,
=IF(HighLightCount(A6:J6)>2,SUM(A6:D6),SUM(E6:J6))
如果您想按特定顏色搜索單元格,以下 UDF 將為您提供幫助。
Function CountCellsByColor(SearchRange As Range, RefCellColor As Range) As Long
Dim indRefColor As Long
Dim cellCurrent As Range
Dim cntRes As Long
Application.Volatile
cntRes = 0
indRefColor = RefCellColor.Cells(1, 1).Interior.Color
For Each cellCurrent In SearchRange
If indRefColor = cellCurrent.Interior.Color Then
cntRes = cntRes + 1
End If
Next cellCurrent
CountCellsByColor = cntRes
End Function
SearchRange
是您要搜索的范圍,而RefCellColor
是您在SearchRange
中查找的顏色格式的參考單元格。
有一種方法可以做到這一點沒有VBA -但它是非常混亂的,你都需要一個“工作”行,並在命名范圍的Excel4宏。 我只是為了完整性而對其進行詳細說明。
第 1 步:創建一個名為“Background_Below”的命名范圍(FORMULAS > NAME MANAGER)並在下面引用: =GET.CELL(63,INDIRECT("r[-1]c",FALSE))
第 2 步:在要計算突出顯示單元格的行下方的行上添加一個工作行,並將公式=Background_Below
放在該行中。 這將是“無顏色”的 0 或“顏色”的 >0(實際值將是與上面單元格顏色最接近的xlColorIndex
值)
第 3 步:在工作行 >0 的地方做一個COUNTIF
正如我所說,它很混亂 - 至少有 9 次在 VBA 中使用用戶定義函數會更好。 但這是可能的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.