Usage of SUMIF formula in the VBA code

G

GreenInIowa

I am trying to use Excel "SUMIF" function in VBA. I was able to do it without
problem by inserting the formula into the cell ( Range(Cells(21, 2), Cells(21
+ RowNumber, 2 + ColumnNumber)).Formula = "=sumIf($a$1:$A$16, $a21,
b$1:b$16)").

But, when I tried to do the same thing using "WorksheetFunction." (
Range(Cells(35, 2), Cells(35 + RowNumber, 2 + ColumnNumber)) =
WorksheetFunction.SumIf(Range(Cells(1, 1), Cells(16, 1)), Range(Cells(21 +
RowNumber, 1), Cells(21 + RowNumber, 1)), Range(Cells(1, 2 + ColumnNumber),
Cells(16, 2 + ColumnNumber)))
) I do not get the same results. It seems to me they are equivalent and
should provide the same results. But, the results says I am wrong and I was
wondering what I am missing here? Thanks.

Here is the entire code:

Sub test()
For RowNumber = 0 To 2
For ColumnNumber = 0 To 3
Range(Cells(21, 2), Cells(21 + RowNumber, 2 + ColumnNumber)).Formula
= "=sumIf($a$1:$A$16, $a21, b$1:b$16)"
Range(Cells(35, 2), Cells(35 + RowNumber, 2 + ColumnNumber)) =
WorksheetFunction.SumIf(Range(Cells(1, 1), Cells(16, 1)), Range(Cells(21 +
RowNumber, 1), Cells(21 + RowNumber, 1)), Range(Cells(1, 2 + ColumnNumber),
Cells(16, 2 + ColumnNumber)))
Next
Next
End Sub
 
T

Toppers

Try

Cells(35 + RowNumber, 2 + ColumnNumber) = _
WorksheetFunction.SumIf(Range(Cells(1, 1), Cells(16, 1)), Cells(21 + _
RowNumber, 1), Range(Cells(1, 2 + ColumnNumber), Cells(16, 2 + ColumnNumber)))

HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top