Count within groups – macro

You have a set of data containing information about a car fleet:

Of course, one car can be used by several drivers and one driver can drive several cars. You are supposed to build a new column showing how many drivers drove each car. You need to keep the dataset as it is and just add the new column.

You can do this without VBA, see here, but for large datasets or when you have several files you might need VBA. So here we go.

 
 
  1. Public Sub CountWithinGroup()
  2.     Dim i
  3.     Dim LastRow, LastCol
  4.     Dim sht As Worksheet
  5.     Dim rs As Recordset
  6.     Dim SQL As String
  7.     Dim FirstColName As String, SecondColName As String
  8.    
  9.    
  10.     ' check if current sheet is the one with the data
  11.    If MsgBox("Macro will run on '" & ActiveSheet.Name & "' sheet!" & vbCr & _
  12.         "Is it OK?", vbOKCancel) = vbCancel Then Exit Sub
  13.        
  14.     Set sht = ActiveSheet
  15.     FirstColName = Cells(1, 1).Value
  16.     SecondColName = Cells(1, 2).Value
  17.    
  18.     LastRow = LastRowOrCol(, , 3)
  19.     LastCol = LastRowOrCol(1, , 3)
  20.    
  21.     Cells(1, LastCol + 1).Value = "Drivers per Car"
  22.    
  23.     ' parse all rows and find the count using SQL
  24.    For i = 2 To LastRow
  25.         SQL = "SELECT DISTINCT " & SecondColName & " FROM [" & sht.Name & "$]  WHERE [" & FirstColName & "] ='" & Cells(i, 1).Value & "'"
  26.         Set rs = RangeToRecordset2(ActiveWorkbook.FullName, SQL)
  27.         Cells(i, LastCol + 1).Value = rs.RecordCount
  28.         Set rs = Nothing
  29.     Next i
  30.    
  31.     MsgBox "Done!"
  32. End Sub

See this file, [1 Sorting] sheet for a dummy dataset.

RangeToRecordset2 function can be found here.

LastRowOrCol function can be found here.

 

Add a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.