Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

VBA alternative to Excel SUMPRODUCT multiple criteria lookup

I have a large spreadsheet with tens of thousands of rows. I want to look up values based on multiple criteria and get the associated values. Currently, I use the SUMPRODUCT function, but with that many rows, it takes many minutes to calculate.

Function:

=SUMPRODUCT((array 1 criteria) * (array2 criteria) * array values) 

Example:

image

=SUMPRODUCT((B15:B23=”John”)*(C15:C23=”North”)*(E15:E23=1)*D15:D23)

Example from here.

Question: Is there a more efficient way to do this type of lookup with multiple criteria - maybe with VBA? I have tried using index match, but it only gives me the value of the first match and I am not sure it is better performance-wise.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you dont want to use Pivot try this.. As all the arguments are range, select desire range for entering the input.

Function VBSumProd(nameRng As Range, nameCrt As Range, regionRng As Range, regionCrt As Range, salesRng As Range, qtrRng As Range, qrtCrt As Range) As Double

Dim i As Long, tempSum As Double
tempSum = 0

For i = 1 To nameRng.Rows.Count
    If WorksheetFunction.And(UCase(nameRng(i)) = UCase(nameCrt), UCase(regionRng(i)) = UCase(regionCrt), qtrRng(i) = qrtCrt) Then
    tempSum = tempSum + salesRng(i)
    End If
Next

VBSumProd = tempSum
End Function

enter image description here

You tried code below which is slow compared to subtotal

Function VBSumProd(nameRng As Range, nameCrt As String, regionRng As Range, regionCrt As String, salesRng As Range, qtrRng As Range, qrtCrt)
Dim nameRngArr, regionRngArr, salesRngArr, qtrRngArr
Dim i As Long, tempSum As Double
tempSum = 0

ReDim nameRngArr(nameRng.Rows.Count)
ReDim regionRngArr(nameRng.Rows.Count)
ReDim salesRngArr(nameRng.Rows.Count)
ReDim qtrRngArr(nameRng.Rows.Count)

For i = 1 To nameRng.Rows.Count
    nameRngArr(i) = nameRng(i)
    regionRngArr(i) = regionRng(i)
    salesRngArr(i) = salesRng(i)
    qtrRngArr(i) = qtrRng(i)
Next

For i = 1 To nameRng.Rows.Count
    If WorksheetFunction.And(UCase(nameRngArr(i)) = UCase(nameCrt), UCase(regionRngArr(i)) = UCase(regionCrt), qtrRngArr(i) = qrtCrt) Then
    tempSum = tempSum + salesRngArr(i)
    End If
Next
VBSumProd = tempSum
End Function

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...