Home » excel » excel – VBA – Using Columns() in Formula

excel – VBA – Using Columns() in Formula

Posted by: admin May 14, 2020 Leave a comment


Right now i am using this code for a SumIf Formula:

Public Sub CommandButton1_Click()

    Dim lastrow As Long

    lastrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1

    i = 4
    calc = "=SUM(SUMIF($A$2:$A$22,N3,$B$2:$B$22),"
    Do Until i = lastrow + 1
        calc = calc & "SUMIF($A$2:$A$22,N" & i & ",$B$2:$B$22),"
        i = i + 1
    ActiveSheet.Range("N" & lastrow + 1 & ":BI" & lastrow + 1).Value = calc & ")"
End Sub 

My Question now is, is there a way that i can change the criteria part in calc = calc & SUMIF($A$2:$A$22,N” & i & “,$B$2:$B$22),” that it jumps from column N to column M till column BI?

In fact my code works fine, but if i move some cells in the table it also moves the formula. And if i add the $ sign it only uses column N.

I tried to add this, but it doesn´t work

i = 4
lCol = 14
calc = "=SUM(SUMIF($A$2:$A$22,N3,$B$2:$B$22),"
Do Until i = lastrow + 1
    calc = calc & "SUMIF($A$2:$A$22," & Columns(i, lCol) & ",$B$2:$B$22),"
    i = i + 1
    lCol = lCol + 1

I hope it is clear what i mean and someone can help me.

How to&Answers:

Try creating a cell and using its address.

calc = calc & "SUMIF($A$2:$A$22," & Cells(i, lCol).address(0, 0) & ",$B$2:$B$22),"



I tried to change the syntax for .address, but i still does not solve my problem. I hope with the following pictures i can explain it better.

In the first picture you can see how my table looks and which cells are used in the formula.

enter image description here

In the second picture i moved some cells to the left and unfortunately the formula also moves. This is what i want to prevent

enter image description here

And if i use .Address(0, 1) the formula looks like this in every column:

=SUM(SUMIF($A$2:$A$22;$N3;$B$2:$B$22),SUMIF($A$2:$A$22;$N4;$B$2:$B$22) … )