简体   繁体   中英

Populating a 2 dimensional Range in excel using sum ifs function in VBA

Data in a sheet with profit which is based on the store and location. Looking to have a matrix with location in one column and stores in a row. For each location and store it would return one value which is the sum of the profit for all stores (there maybe multiple stores in a particular location) in that location.

This would be the excel function:

=SUMIFS(Sheet2!$C$2:$C$6,Sheet2!$A$2:$A$6,Sheet1!$A5,Sheet2!$B$2:$B$6,Sheet1!B$4)

Try something like,

with sheets("Sheet1")
    with .range("B5:Z99")
        .formula = "=SUMIFS(Sheet2!$C$2:$C$6, Sheet2!$A$2:$A$6, Sheet1!$A5, Sheet2!$B$2:$B$6, Sheet1!B$4)"
        .value = .value
    end with 
end with

Essentially, write the formula into the block of cells then revert the formulas' results to their values.

EDIT for dynamic last row:

dim lr as long
lr = Sheets("Sheet2").cells(rows.count, 3).end(xlup).row

Then the formula assignment would be:

.formula = "=SUMIFS(Sheet2!$C$2:$C$" & lr & ", Sheet2!$A$2:$A$" & lr & ", Sheet1!$A5, Sheet2!$B$2:$B$" & lr & ", Sheet1!B$4)"

EDIT: Named Ranges:

If you move to a formula utilizing named ranges to define the extents of the data being examined, use the same MATCH formula to define the limits of different columns.

Example: In the above SUMIFS, you could use named ranges for Sheet2's columns A, B and C. Let's call the named ranges ws2colA, ws2colB and ws2colC . We know that we are summing columns C so use the row of the last number in column C to define the ranges for each of the columns.

ws2colA - Applies to:
=Sheet2!$A$2:INDEX(Sheet2!$A:$A, MATCH(1e99, Sheet2!$C:$C))

ws2colB - Applies to:
=Sheet2!$B$2:INDEX(Sheet2!$B:$B, MATCH(1e99, Sheet2!$C:$C))

ws2colC - Applies to:
=Sheet2!$C$2:INDEX(Sheet2!$C:$C, MATCH(1e99, Sheet2!$C:$C))

The formula assignment becomes:

.formula = "=SUMIFS(ws2colC, ws2colA, Sheet1!$A5, ws2colB, Sheet1!B$4)"

Using the same formula to define the extents of each named range column will prevent mismatched range references in the SUMIFS.

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