[英]How do I cross-reference between two worksheets and sum/group by occurances on 3rd sheet?
這將為您工作,但可能會有人可以做得更好。 我希望我的代碼很冗長,但可以根據需要將其精簡。
在第一個表中,在名為“ 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.