如果Excel VBA识别范围条件符合VBA的计数

是否有可能使用CountIf在VBA中返回一个范围?

Application.WorksheetFunction.CountIf(MyRange,x)> 1

我想采取CountIf在MyRange中findX的范围,并对其进行操作。

提前致谢。

发现相当快:

Sub FindX() Dim r As Range Set r = Cells.Find(What:="X", After:=Range("A1")) If Not r is nothing Then MsgBox r.Address(0, 0) End Sub 

它确实出现查找可能比CountIF更快。 我使用相当数量的数据在下面做了一个例子。 有了这个发现,以及不能够操纵我的第二个范围,如果,足以让我继续在代码中使用Find。 另外,CountIF不区分大小写! 谢谢各位的意见。

 Sub Test() Dim i As Integer Dim Range1 As Range 'Range1 values will always have a match in Range2 Dim Range2 As Range 'Range2 values will only appear once and are never duplicated Dim t As Long t = Timer Set Range1 = Range("A1:A100") Set Range2 = Range("B1:B100000") For i = 1 To 30000 Cells(i, 1).Value = i Cells(i, 2).Value = i Next i 'i overflow error after 30000 or so 'This is the only part of code that changed 'First 100 cells of Column A and B turn red For Each x In Range1 Set y = Range2.Find(What:=x, LookIn:=xlValues, _ LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _ MatchCase:=True, SearchFormat:=False) If Not y Is Nothing Then y.Interior.ColorIndex = 3 x.Interior.ColorIndex = 3 End If Next x MsgBox ("done " & Timer) 'find method time = ~56166 'countif method = ~56232 End Sub 

 Sub Test() Dim i As Integer Dim Range1 As Range 'Range1 values will always have a match in Range2 Dim Range2 As Range 'Range2 values will only appear once and are never duplicated Dim t As Long t = Timer Set Range1 = Range("A1:A100") Set Range2 = Range("B1:B100000") For i = 1 To 30000 Cells(i, 1).Value = i Cells(i, 2).Value = i Next i 'i overflow error after 30000 or so 'This is the only part of code that changed 'First 100 cells of Column A turn red For Each x In Range1 If Application.WorksheetFunction.CountIf(Range2, x) > 0 Then 'dunno where Range2 match is - cannot manipulate x.Interior.ColorIndex = 3 End If Next x MsgBox ("done " & Timer) 'find method time = ~56166 'countif method = ~56232 End Sub