[英]Modify VBA To Account For Conditional Formatting
我試圖在 Excel 2016 中使用類似 COUNTIF 的函數按背景顏色匯總一系列單元格...... 3 種不同顏色(綠色、黃色、紅色)代表 3 種不同的“狀態”(第一大、第二大) ,第三大)。 我設法通過使用此 VBA 編碼使其工作:
Function Countcolour(rng As Range, colour As Range) As Long
Dim c As Range
Application.Volatile
For Each c In rng
If c.Interior.ColorIndex = colour.Interior.ColorIndex Then
Countcolour = Countcolour + 1
End If
Next
End Function
但是,此特定代碼未考慮條件格式。
例如,我嘗試有條件地格式化一組數據,以突出顯示其第一大值綠色、第二大黃色、第三大紅色。 我在另一個塊中使用這個 VBA 函數來計算所有綠色高光的數量。 但是,由於條件格式,它不會選擇單元格的背景顏色。
我確定我遺漏了一些明顯的東西......我覺得If
條件的第一部分應該是某種形式的c.FormatCondition.Interior
,但我已經嘗試了主題的變體,但沒有成功。
在此先感謝您提供的任何幫助!
這是很多人嘗試做的事情,包括我。
互聯網上有一些有用的代碼,如http://www.cpearson.com/excel/CFColors.htm但經過大量搜索后,我發現只有一個答案在 excel 中使用 vba 獲得條件格式的顏色並且它有效!
解決方法很簡單:
你可以使用
.cells(1,1).displayformat.interior.color
或
.cells(1,1).displayformat.interior.colorIndex
示例:
Function CountColor(ByRef rng As Range, ByRef color As Long) As Variant
Dim total: total = 0
If (Not (rng Is Nothing)) Then
Dim element As Variant
For Each element In rng
total = total - (element.DisplayFormat.Interior.color = color) ' MINUS because TRUE evaluates to -1
Next element
End If
CountColor = total
End Function
Sub test_countColors()
With Sheet1
Dim rng As Range
Dim color As Long
Dim total As Long
Set rng = Range(.Cells(1, 1), .Cells(3500, 55)) ' Or anay other range
color = 8438015 ' Or any other color
total = CountColor(rng, color)
MsgBox "Total= " & total
End With
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.