简体   繁体   中英

VBA to FillDown Formula with changing cell reference

I have a Sumifs function to be done in macro with 2 criterias. my excel file is quite big. So my code looks like this :

Sub SumIfs()
ThisWorkbook.Sheets("Sheet1").Activate
Range("L2") = Application.WorksheetFunction.SUMifs(Range("G:G"),Range("A:A"),"Pen",Range("F:F"),"John")
End Sub

But i would like to change the "Pen" to its cell reference, which means "A2" and " John" remains constant for all the cells down in the F:F range. And the to fill the formula down for all the cells below. I used this code,

Application.WorksheetFunction.SUMifs(Range("G:G"),Range("A:A"), A2,Range("F:F"),"John")

But it only shows the value for A2 down in the cells when I did the filldown function. Please Help me with this. Thanks in Advance.

It sounds like you are after something like:

Sub SumIfs()
    With ThisWorkbook.Sheets("Sheet1")
        .Range("L2:L" & .Range("G" & .Rows.Count).End(xlUp).Row).Formula = _
                    "=SUMIFS(G:G,A:A,A2,F:F,""John"")"
    End With
End Sub

If you want the value , rather than the formula , inserted into column L, you could extend that code to:

Sub SumIfs()
    Dim LastRow As Long
    With ThisWorkbook.Sheets("Sheet1")
        'Assume we want to create values for every cell in column L down until
        'we get to the last cell in column G
        LastRow = .Range("G" & .Rows.Count).End(xlUp).Row
        'Paste the formula
        .Range("L2:L" & LastRow).Formula = _
                    "=SUMIFS(G:G,A:A,A2,F:F,""John"")"
        'Convert to values
        .Range("L2:L" & LastRow).Value = _
                   .Range("L2:L" & LastRow).Value
    End With
End Sub

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