CountIf Excel VBA识别范围条件符合VBA的位置

时间:2014-02-26 14:31:54

标签: excel vba excel-vba

是否可以使用CountIf在VBA中返回范围?

  

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

我想把CountIf在MyRange中找到X的范围,并操纵它。

提前致谢。

2 个答案:

答案 0 :(得分:3)

查找非常快:

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

答案 1 :(得分:0)

看起来确实比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