Find的vba不能正常工作

时间:2013-08-08 20:59:08

标签: excel excel-vba vba

这是一个非常基本的问题,不要尖叫我,因为我不是vba专家。

所以我们走了,我创建了以下vba函数

Public Function GetDuplicateCount(value As String) As Integer

    Dim counter As Integer

    counter = 0

    With Worksheets(1).Range("A:A")
        Set c = .Find(value, _
                    LookIn:=xlValues, _
                    LookAt:=xlWhole, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlNext, _
                    MatchCase:=False)

        If Not c Is Nothing Then
            firstAddress = c.Address
            Do
                counter = counter + 1
                Set c = .FindNext(c)
            Loop While Not c Is Nothing

        End If
    End With

    GetDuplicateCount = counter
End Function

以下是我的Excel值

A

1 IND

2美国

3 CAN

4 IND

5 CAN

6美国

每当我搜索任何值时,它都会返回一个不知道的东西。这个功能有什么问题吗?

e.g。 GetDuplicateCount( “IND”)

2 个答案:

答案 0 :(得分:2)

得到它......终于

两件事FindNext不是workign,所以@kazjaw建议我试过.find,这是工作代码。别忘了给出附加条件,那就是“firstAddress<> c.Address”

Public Function GetDuplicateCount(value As String) As Integer

    Dim counter As Integer
    counter = 0

    With Worksheets(1).Range("A:A")
        Set c = .Find(value, _
                    LookIn:=xlValues, _
                    LookAt:=xlWhole, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlNext, _
                    after:=Cells(1, 1), _
                    MatchCase:=False)

        If Not c Is Nothing Then
            firstAddress = c.Address
            Do
                counter = counter + 1
                Set c = .Find(value, _
                    LookIn:=xlValues, _
                    LookAt:=xlWhole, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlNext, _
                    after:=c, _
                    MatchCase:=False)
            Loop While Not c Is Nothing And firstAddress <> c.Address

        End If
    End With

    GetDuplicateCount = counter
End Function

答案 1 :(得分:1)

为什么不使用本机Countif功能?

=COUNTIF(A:A,"IND")