简体   繁体   中英

VBA - Using Columns() in Formula

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.

尝试创建一个单元并使用其地址。

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

@Jeeped:

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.

在此处输入图片说明

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

在此处输入图片说明

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) ... )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM