【问题标题】:Counting multiple occurrences计算多次出现
【发布时间】:2019-07-10 14:15:01
【问题描述】:

我正在寻找一个公式来列出仅当值大于 2 时出现的值;结果将如图所示。

例如,如果一个值重复 2 次,则显示为“2”,重复 3 次则显示为“3”。因此,如果该范围内有两个数字重复,则它将显示为“32”,如下图所示。 (数字之间不需要逗号)。谢谢。

【问题讨论】:

  • 我可以用公式为您提供模式,22122111,3332211144411411。但我认为你需要 vba 才能得到你正在寻找的答案。
  • 如果可能的话,我的第一选择是公式。但我也可以使用 vba 解决方案。
  • 如果一个数字可以重复的次数是固定的,如果一个超长的公式,你可以到达那里。
  • 我很惊讶这实际上对于公式来说太复杂了。

标签: excel excel-formula


【解决方案1】:

这是一个简单的 UDF:

Function mycount(rng As Range) As String

Dim str As String
Dim rngcnt As Range
For Each rngcnt In rng
    If InStr("," & str & ",", "," & rngcnt.Value & ",") = 0 Then
        If Application.WorksheetFunction.CountIf(rng, rngcnt) > 1 Then
            mycount = mycount & Application.WorksheetFunction.CountIf(rng, rngcnt)
            str = str & "," & rngcnt
        End If
    End If
Next rngcnt
End Function

所以你在工作表上的电话是:

=mycount(A2:H2)

然后抄下来。

【讨论】:

  • 斯科特,这很好用。谢谢。如果我想在计数末尾添加一个字母,说“r”,使其看起来像 22r、32r、4r 等。我应该在 vba 中添加什么?我可以玩公式,但不能玩 vba。
  • 你可以把它放在代码中,或者只使用=mycount(A2:H2) & "r"作为公式@Max。注意:请下次将该要求放在原始帖子中。请记得标记为正确。
  • 是的,我很抱歉,我期待一个公式,我忘记了 vba。谢谢。
  • 谢谢。尼扎姆。你不需要删除它。如果你愿意,你可以保留它作为替代品。 VBA 学习者也可以与代码进行比较。
  • 谢谢。我的答案也变得更大,因为我在发现字符后对它们进行了排序。
【解决方案2】:

我得到它的方法是定义一个 VBA 函数。这个函数使用字典,所以有必要添加对“Microsoft Scripting Runtime”的引用(看here)。另外,我使用了一个函数来对来自here的字符串中的字符进行排序

Function Repetitions(rng As Range)

    Dim dict As New Scripting.Dictionary
    Dim res() As Integer

    For aux = 1 To rng.Count
        Dim numero As Integer
        numero = rng.Cells(1, aux).Value
        If Not dict.Exists(numero) Then
            dict.Add numero, 1
        Else
            dict(numero) = dict(numero) + 1
        End If
    Next aux

    Dim result As String
    result = ""
    For aux = 0 To UBound(dict.Items)
        If dict.Items(aux) > 1 Then result = result & dict.Items(aux)
    Next aux

    While Len(result)
        iTemp = 1
        Temp = Left(result, 1)

            For I = 2 To Len(result)
            If StrComp(Mid(result, I, 1), Temp, vbTextCompare) = 0 Then
                If StrComp(Mid(result, I, 1), Temp, vbBinaryCompare) = 1 Then
                    Temp = Mid(result, I, 1)
                    iTemp = I
                End If
            End If

            If StrComp(Mid(result, I, 1), Temp, vbTextCompare) = 1 Then
                    Temp = Mid(result, I, 1)
                    iTemp = I
                End If
            Next I

        Repetitions = Repetitions & Temp
        result = Left(result, iTemp - 1) & _
                            Mid(result, iTemp + 1)
    Wend


End Function

毕竟,你可以在Excel中使用函数作为公式,例如如下调用它:

=Repetitions(A2:F2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多