简体   繁体   中英

CountIfs variable range

As written, I am not having problems with the code shown below.

However, I will not always have 5520 rows, so I am trying to replace range("L2:L5520") with range(cells(2,12),cells(rng.Rows.Count,12)) where rng is predefined above as range and a watch on rng.Rows.Count confirms the present value is 5520.

For r = 7 To 11
    For c = 2 To 5
        Cells(r, c) = Application.WorksheetFunction.CountIfs(Sheets("PA2_Data").range("L2:L5520"), Sheets("PA2_Tables").Cells(6, c), Sheets("PA2_Data").range("F2:F5520"), Sheets("PA2_Tables").Cells(r, 1))
    Cells(r, 6) = Application.WorksheetFunction.Sum(Sheets("PA2_Tables").range(Cells(r, 2), Cells(r, 5)))
Next r

With range(cells(2,12),cells(rng.Rows.Count,12)) I get an error 1004, Application-defined or object-defined error.

Any suggestions?

Not sure if rng was declared such that the statement you have will work, but what you likely want to do is use a "last row" variable instead of the rng one you are using.

So try this:

 Dim lastrow As long
 Dim ws As Worksheet

 Set ws = Sheets("PA2_Tables")
 lastrow = ws.Cells(ws.rows.count, "A").end(xlUp).row

 ....

For r = 7 To 11
    For c = 2 To 5
        Cells(r, c) = Application.WorksheetFunction.CountIfs(Sheets("PA2_Data").range("L2:L" & lastrow), Sheets("PA2_Tables").Cells(6, c), Sheets("PA2_Data").range("F2:F" & lastrow), Sheets("PA2_Tables").Cells(r, 1))
        Cells(r, 6) = Application.WorksheetFunction.Sum(Sheets("PA2_Tables").range(Cells(r, 2), Cells(r, 5)))
    Next c
Next r

With range(cells(2,12),cells(lastrow,12)) 


......

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