我对VBA很新,经过大量搜索后,我无法找到任何帮助来解决以下问题。
我有一个包含大量数据的相当大且复杂的表。表格中的数据已经过条件格式化,具有不同的颜色填充。使用以下代码,我可以计算每个范围内某种颜色的单元格数。
但是我希望用例如某些东西替换范围;如果列C值与“苹果”匹配,并且IF行3值与“农场A”匹配则在该区域内计数绿色填充。
我到目前为止使用的代码如下。
Dim rng As Range
Dim lColorCounter As Long
Dim rngCell As Range
Sheets("Matrix").Select
Set rng = Sheet1.Range("F140:O150")
For Each rngCell In rng
If Cells(rngCell.Row, rngCell.Column).DisplayFormat.Interior.Color = RGB(185, 255, 185) Then
lColorCounter = lColorCounter + 1
End If
Next
Sheets("Summary").Activate
Sheet3.Range("C4") = lColorCounter
lColorCounter = 0
希望这是有道理的,任何帮助都将得到真正的赞赏。谢谢!
正如评论中所讨论的,这有一个动态行循环(检查Apples的值)和一个动态列循环(检查单元格的颜色)。
第二个循环的范围由合并单元格(“Farm A”)的大小决定,该单元格在C2
单元格中开始。因此,如果将Farm A
合并单元格更改为跨越20列,则循环将扩展为这20列。
Option Explicit
Sub test()
Dim i As Long, FarmA As Integer, MyCell As Range, lColorCounter As Long
Dim Matrix As Worksheet: Set Matrix = ThisWorkbook.Sheets("Matrix")
Application.ScreenUpdating = False
With Matrix
FarmA = .Range("C2").CurrentRegion.Count + 2 'Determine size of merged cell "FarmA"
For i = 3 To .Range("B" & .Rows.Count).End(xlUp).Row 'Loop through used rows in Col B
If .Range("B" & i) = "Apples" Then 'If condition is met, move to next line, else, check next row
For Each MyCell In .Range(.Cells(i, 3), .Cells(i, FarmA)) 'set serach range
If MyCell.DisplayFormat.Interior.Color = RGB(185, 255, 185) Then 'search for format
lColorCounter = lColorCounter + 1
End If
Next MyCell
End If
Next i
End With
Application.ScreenUpdating = True
MsgBox lColorCounter
End Sub