簡體   English   中英

如何在兩個工作表之間進行交叉引用,並在第三工作表上按發生次數對總和/組進行交叉引用?

[英]How do I cross-reference between two worksheets and sum/group by occurances on 3rd sheet?

我對excel工作表非常陌生,需要一些幫助來解決此問題。 第一本Cookbook列出了各部門及其各自的食譜。 部門和產品之間存在多對多關系。

在此處輸入圖片說明

我有另一片Ingredients ,其中列出了Ingedients什么Recipes他們屬於:

在此處輸入圖片說明

我想在標題為“ Category x Ingredient Totals ”的第三張表中按成分獲取每個類別的Category x Ingredient Totals

在此處輸入圖片說明

成分表中的X隱式表示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)

自然,您需要用需要引用的實際單元格替換最后兩個參數($ A16 =“類別1”和B $ 15 =“成分1”),它們當前相對於我的工作表以及我放置的位置我的價值觀。

我希望這個對你有用。 我認為確實如此,它突出顯示了矩陣交集“類別3”,“成分3”實際上是2,而不是1...。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM