简体   繁体   中英

Count based on multiple conditions

So I have looked at count & countif but not seeing exactly what I am trying to accomplish. Basically I have 3 columns of data. sales man, city, date

Data could look like the following:

SM1     City1    07/01/2010
SM2     City1    07/01/2010
SM1     City2    07/01/2010
SM3     City1    07/01/2010

I'd like to add a 4th column that displays a count for how many sales men visited that city on that date. So I'd want to end up with :

SM1     City1    07/01/2010     3
SM2     City1    07/01/2010     3
SM1     City2    07/01/2010     1
SM3     City1    07/01/2010     3

So I need to figure out counts based on both the city and the date. Any help would be appreciated. Just some pointers would be most welcome. I'd like to use VBA and be able to have it dynamically determine the number of rows as it will not be static.

I'm not sure why you'd need VBA for this, a simple COUNTIFS formula will work for you. Using your provided example data, use this formula in cell D1 and copy down:

=COUNTIFS(B:B,B1,C:C,C1)

I agree with @tigeravatar that the formula =COUNTIFS(B:B,B1,C:C,C1) will do it for you. Just double-click the bottom right hand corner of the last row in column D and let if fill down for you.

If you're bent on using VBA for whatever reason though, you could try something like this, which presumes you already have the aforementioned formula in the last row of column D:

Sub countIf()

'Get the last row in the sheet, presumably where your A/B/C columns end
sheetLastRow = ActiveSheet.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row

'Get the last row of the D column where your formula should be
countIfLastrow = ActiveSheet.Range("D" & Rows.Count).End(xlUp).Row

'Copy the formula down the D column to the end of your A/B/C columns,
'    just like clicking the corner of the cell
ActiveSheet.Range("D" & countIfLastrow).AutoFill Destination:=ActiveSheet.Range("D" & countIfLastrow & ":D" & sheetLastRow)

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