如何从CountIF中获取与活动的值和颜色相匹配的单元格数目,循环代码等于从VBA Excel中的CountIF中find的单元格数量?

我还有一个类似问题的问题。 我在VBA中有一个函数,它查找与活动单元格的date和单元格颜色相匹配的单元格,find下一个匹配的单元格后,它将转到H列中相应的单元格,并将其高亮显示为“青色”。 这工作正是我想要的,但我必须每次点击运行macros。 我希望函数能够在所有匹配的单元格上工作。 我想使用Do Until循环,发现@ http://www.excel-easy.com/vba/examples/do-until-loop.html ,但要做到这一点,我需要知道匹配的单元格的数量使循环停止。

我的工作代码:

Sub Test1() ' ' Test1 Macro ' ' Dim CellColor As Variant Dim SearchDate As String, FoundAt As String CellColor = Range("B" & ActiveCell.Row).Interior.Color SearchDate = Range("B" & ActiveCell.Row).NumberFormat Range("B" & ActiveCell.Row).Select Application.FindFormat.Clear Application.FindFormat.NumberFormat = SearchDate Application.FindFormat.Interior.Color = CellColor Cells.Find(What:="", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _ xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False _ , SearchFormat:=True).Activate End Sub 

我想使用的循环代码在上面的链接中find:

 Dim i As Integer i = 1 Do Until i > 6 Cells(i, 1).Value = 20 i = i + 1 Loop 

我有这个CountIF的代码:

 Dim cellCount As Integer cellCount = Application.WorksheetFunction.CountIf(Range("B1:B30"), "7/22/2016") 'Count matching MsgBox cellCount 'test to see if count works 

但是有两个问题呢。 问题一,我必须在代码中手动inputdate“7/22/2016”而不是使用variables“SearchDate”。问题二是它只searchdate,而不是过滤date的单元格颜色我的电子表格。

所以我的问题是在这一切。 如何获得满足活动单元格的date和颜色值的date数量,并将该数字携带到要在循环中使用的variables中?

如果有更有效的方法来做到这一点,请告诉我。 提前谢谢了!!!

参考图片:

屏幕截图显示date和颜色的电子表格。

如果我正确理解你的问题,那么这就是你将要寻找的

 Sub Test1() Dim CellColor As Variant Dim SearchDate As String For i = 1 To 19 CellColor = Cells(i, 2).Interior.Color SearchDate = Cells(i, 2).NumberFormat If Cells(i, 2).Value <> "" Then For j = i To 19 If i <> j And CellColor = Cells(j, 2).Interior.Color And SearchDate = Cells(j, 2).NumberFormat Then Cells(j, 8).Interior.Color = RGB(0, 255, 255) End If Next j End If Next i End Sub 

下一个函数将计算B列中的所有匹配单元格。它不会突出显示任何单元格。 你将不得不自己添加这个部分。

为了使用它,只需在您的代码中添加以下内容:

 Dim x As Integer x = countMatchingCells 

function:

 Function countMatchingCells() As Integer Dim CellColor As Variant Dim SearchDate As String, FoundAt As String Dim i As Integer Dim counter As Integer CellColor = Range("B" & ActiveCell.Row).Interior.Color SearchDate = Range("B" & ActiveCell.Row).NumberFormat counter = 0 'assuming we are working on sheet1: For i = 1 To Sheets(1).Cells(Sheets(1).Rows.Count, 2).End(xlUp).Row If Cells(i, 2).Interior.Color = CellColor And _ Cells(i, 2).NumberFormat = SearchDate Then countMatchingCells = countMatchingCells + 1 'you can write more code here, for example if you want to highlight cells once you found a match End If Next i End Function