Auto-group entries in Excel

This macro creates outline groups automatically based on values in a sorted grouping column. e.g. Given this set of data:

A 1
A 2
A 3
B 1
B 2
C 1
C 2
C 3
C 4

the macro will create three collapsible groups: A, B and C.

The macro assumes that your grouping direction is 'Summary rows above detail'.

Sub AutoGroupEntries()
  'Application.ScreenUpdating = False 'disable screen update while running
  'Define Variables - these will be set based on the current cellpointer position
  Dim groupingColumn As Integer  'index for the (sorted) column containing group identifiers
  Dim firstRow As Integer 'number of the first row of data for grouping
  Dim lastRow As Integer 'number of the first row of data for grouping
  groupingColumn = ActiveCell.Column
  firstRow = ActiveCell.Row
  lastRow = ActiveSheet.UsedRange.Rows.Count
  'remove any existing outlining
  'step through rows from firstRow, grouping items until lastRow is reached
  Dim i, groupStart, groupEnd As Integer
  groupStart = firstRow + 1 'for the first group
  For i = firstRow + 1 To lastRow + 1
    If Cells(i, groupingColumn).Value <> Cells(i - 1, groupingColumn).Value Then  'at end of group
      groupEnd = i - 1
      Rows(groupStart & ":" & groupEnd).Select  'select group of rows
      Selection.Rows.Group  'create group for selected rows
      groupStart = groupEnd + 2 'set start for the next group
    End If
  Next i
  Application.ScreenUpdating = True 'enable screen update when done
End Sub