# Sumif with VBA

#### Nelson78

##### Active Member
Hello everybody.

I'm running on empty with the following matter.

Writing this in a cell it works fine:

Code:
=SUMIF(H19:H1891,"black",G19:G1891)

Now, in my VBA code:

lastcol + 1 = column in which you can find the values to sum
lastcol + 2 = column in which you can find the criteria
criteria = "black"
row = from 19 (fix) to lr2

How can I build the calculation?

Thank's.

Last edited:

### Excel Facts

Author John Walkenbach was Mr Spreadsheet until his retirement in June 2019.

#### mumps

##### Well-known Member
Can you post a screenshot of what you data looks like? What does "lastcol" represent?

#### Marcelo Branco

##### MrExcel MVP
Maybe something like this

Code:
Dim myVar as Double

myVar = Application.SumIf(Range(Cells(19, lastcol + 2), Cells(lr2, lastcol + 2)), "Black",Range(Cells(19, lastcol + 1), Cells(lr2, lastcol + 1)))
M.

Last edited:

#### steve the fish

##### Well-known Member
If you want to place the formula in a cell maybe:

Code:
lastcol = 6
lr2 = 1891
criteria = "black"
Set rng = Range(Cells(19, lastcol + 2), Cells(lr2, lastcol + 2))
Set sum_rng = Range(Cells(19, lastcol + 1), Cells(lr2, lastcol + 1))

Range("A1").Formula = "=SUMIF(" & rng.Address & ",""" & criteria & """," & sum_rng.Address & ")"

#### Nelson78

##### Active Member
Maybe something like this

Code:
Dim myVar as Double

myVar = Application.SumIf(Range(Cells(19, lastcol + 2), Cells(lr2, lastcol + 2)), "Black",Range(Cells(19, lastcol + 1), Cells(lr2, lastcol + 1)))
M.
Yes, perfect.

Just one clarification: why Double?

1,101,774
Messages
5,482,837
Members
407,365
Latest member
Leah Ashley

### This Week's Hot Topics

• Finding issue in If elseif else with For each Loop
Finding issue in If elseif else with For each Loop I have tried this below code but i'm getting in Y column filled with W005. Colud you please...
• MsgBox Error
Hi Guys, I have the below error show up when i try and run my macro in File1 but works fine if i copy and paste the same code into file2. [ATTACH...
• CELL FORMAT - IF CONDITION
My Cell Format is [B]""0.00" Cr". [/B]But in the cell, it is showing 123.00 for editing. (123 is entry figure). (Data imported from other...
• Show numbers nearly the same
Is this possible. I have a number that can change very time eg 0.00001234 Then I have a lot of numbers 0.0000001, 0.0000002, 0.00000004...