【问题标题】:finding combinations multiple rows excel查找组合多行excel
【发布时间】:2017-05-24 00:23:21
【问题描述】:

我在 excel 中有如下数据:

Ingredient1  Ingredient2  Ingredient3  Ingredient 4
Salami       Tuna         Peperoni     Mushroom
Salami       Peperoni     Mushroom
Salami       Mushroom

成分是列名,有些单元格是空的,因为没有足够的成分。

我想获取组合和计数,例如:

Salami, Tuna      1 
Salami, Peperoni  2
Salami, Mushroom  3

这可能吗?

【问题讨论】:

  • 意大利腊肠,金枪鱼 1?对吗?
  • 如果 'Salami' 也发生变化,您只需使用 COUNTIFCOUNTIFS 即可实现此目的

标签: excel vba


【解决方案1】:

我咬了。如果你愿意,你可以试一试。它需要针对您的特定输入和输出进行修改,但它可以工作。它将第一列与每个单独的成分和计数结合起来。即它不会返回“蘑菇,意大利辣香肠”之类的组合,但这不是您在问题中指定的内容

Option Explicit
Public Sub CountDemo()
    Dim dict As Object
    Dim rng As Range
    Dim c
    Dim Ing As String
    Dim i As Long
    Dim key
    '' Set up for dictionary object
    Set dict = CreateObject("Scripting.Dictionary")
    '' Declare data range
    With Sheet1
        Set rng = .Range(.Cells(2, 2), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 4))
    End With

    '' Loop through each c in range
    For Each c In rng.Cells
        '' Test if cell is null
        If Not c.Value2 = vbNullString Then
            '' Set Ingredient combo to variable
            Ing = c.Offset(0, 1 - c.Column).Value2 & ", " & c.Value2
            '' Test if value exists in dictionary
            If dict.exists(Ing) Then
                '' If exists increase count by 1
                dict(Ing) = dict(Ing) + 1
            Else
                '' If doesn't exist then add to dictionary and set to default value of 1
                dict.Add key:=Ing, Item:=1
            End If
        End If
    Next c

    '' Output results
    'Starting row
    i = 8
    '' Loop through each ingredient combo
    For Each key In dict.keys
        '' Print to sheet values
        With Sheet1.Cells(i, 1)
            .Value2 = key
            .Offset(0, 1).Value2 = dict(key)
        End With
        i = i + 1
    Next key
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 2013-09-19
    • 2019-06-04
    • 2018-04-05
    相关资源
    最近更新 更多