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

excel – VBA – Using Columns() in Formula

Questions:

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
Loop
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
Loop
``````

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

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),"
``````