[英]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.