VBA-通过匹配列和行值来设置范围

时间:2018-07-16 13:40:43

标签: excel vba

我是VBA的新手,经过大量搜索,我仍然无法找到解决以下问题的帮助。

我有一个相当大而复杂的表,其中包含很多数据。表中的数据已被条件格式化为具有不同的颜色填充。使用以下代码,我能够计算每个范围内某种颜色的像元数。

但是我想用例如类似的东西代替范围;如果C列的值与“ Apples”匹配,并且如果第3行的值与“ Farm 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

希望这是有道理的,任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

如评论中所述,它具有一个动态行循环(检查 Apples 的值)和一个动态列循环(检查单元格的 color )。

第二个循环的范围由在单元格C2中开始的合并单元格(“ Farm A”)的大小确定。因此,如果将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