如何在两个工作表之间进行交叉引用,并在第三工作表上按发生次数对总和/组进行交叉引用?

时间:2019-01-28 00:42:42

标签: excel excel-formula cross-reference

我对excel工作表非常陌生,需要一些帮助来解决此问题。第一页Cookbook列出了部门及其各自的配方。部门和产品之间存在多对多的关系。

enter image description here

我还有一张工作表Ingredients,其中列出了Ingedients及其所属的Recipes

enter image description here

我想在标题为Category x Ingredient Totals的第三张纸上按成分获取每个类别的总和:

enter image description here

“成分”表中的X隐式表示1,但是我不确定如何转换(除其他外)。

1 个答案:

答案 0 :(得分:1)

这将为您工作,但是可能会有人可以做得更好。我希望我的代码很冗长,但可以根据需要将其精简。

在第一个表格中,为数据创建一个范围(不包括标题),该范围称为“ rngCategoriesToRecipes

接下来,在第二个表(这次包括标题)上创建一个范围,称为“ rngRecipetoIngredients ”。

第三,将以下代码添加到VBA编辑器中的新模块中...

Public Function CalculateCategoryToIngredients( _
        ByVal rngCategoriesToRecipesMapping As Range, _
        ByVal rngRecipesToIngredientsMapping As Range, _
        ByVal strCategory As String, _
        ByVal strIngredient As String) As Long

    Application.Volatile

    Dim strThisCategory As String, strThisRecipe As String, strThisIngredient As String, strRecipes As String, objCell As Range
    Dim lngRow As Long, lngCol As Long, arrRecipes, bIsRelevant As Boolean, strThisValue As String, lngCount As Long

    ' Process each of the different categories and they're mappings to recipes.
    For i = 1 To rngCategoriesToRecipesMapping.Rows.Count
        strThisCategory = rngCategoriesToRecipesMapping.Cells(i, 1)
        strThisRecipe = rngCategoriesToRecipesMapping.Cells(i, 2)

        ' Get all of the recipes related to the category passed in.
        If strThisCategory = strCategory Then
            strRecipes = strRecipes + "," + strThisRecipe
        End If
    Next

    arrRecipes = Split(Mid(strRecipes, 2), ",")

    ' Now process the mapping from the recipes to the ingredients.
    For lngRow = 2 To rngRecipesToIngredientsMapping.Rows.Count
        For lngCol = 2 To rngRecipesToIngredientsMapping.Columns.Count
            strThisValue = Trim(rngRecipesToIngredientsMapping.Cells(lngRow, lngCol))
            strThisRecipe = rngRecipesToIngredientsMapping.Cells(lngRow, 1)
            strThisIngredient = rngRecipesToIngredientsMapping.Cells(1, lngCol)

            bIsRelevant = False

            For i = 0 To UBound(arrRecipes)
                If arrRecipes(i) = strThisRecipe Then
                    bIsRelevant = True
                    Exit For
                End If
            Next

            If bIsRelevant And strThisValue <> "" And strIngredient = strThisIngredient Then
                lngCount = lngCount + 1
            End If
        Next
    Next

    CalculateCategoryToIngredients = lngCount
End Function

最后,将此公式添加到要计算并向下填充的范围内的第一个单元格中。

=CalculateCategoryToIngredients(rngCategoriesToRecipes,rngRecipetoIngredients,$A16,B$15)

自然,您需要用您需要引用的实际单元格替换最后2个参数($ A16 =“类别1”和B $ 15 =“成分1”),它们当前相对于我的工作表和我放置我的价值观的地方。

我希望它对您有用。我认为确实如此,它突出显示了矩阵交集“类别3”,“成分3”实际上是2,而不是1...。