2

这是一个非常基本的问题,不要对我大喊大叫,因为我不是 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值

一个

1个IND

2 美国

3 罐

4 IND

5 罐

6 美国

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

例如 GetDuplicateCount("IND")

4

3 回答 3

3

明白了……终于

两件事 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
于 2013-08-09T14:24:57.367 回答
1

为什么不使用本机 Countif 函数?

=COUNTIF(A:A,"IND")
于 2013-08-08T21:02:32.827 回答
0

这是一个老问题,但在 O365 中它不起作用,因为第一个地址没有退出条件,所以它循环直到它爆炸。请注意,Is Nothingand.Address必须单独测试,否则如果范围没有,您将收到错误消息。

下面添加了退出条件:

Public Function GetDuplicateCount(value As String) As Integer

    Dim counter As Integer
    Dim c As Range
    Dim firstAddress As String

    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
                Debug.Print c.Address
                counter = counter + 1
                Set c = .FindNext(c)
                If c Is Nothing Then Exit Do
            Loop While Not c.Address = firstAddress

        End If
    End With

    GetDuplicateCount = counter
End Function
于 2021-01-15T02:00:46.670 回答