Quando la struttura automatica in Microsoft Excel non funziona

Quando la struttura automatica in Microsoft Excel non funziona (Dati-Struttura-Raggruppa-Struttura automatica), possiamo scrivere una semplice macro e risolvere il problema.

La struttura automatica funziona quando Microsoft Excel trova una formula che consente di identificare le righe (o colonne) da raggruppare.

Ho ricevuto un insieme di righe che non avevano formule, ma dovevano essere raggruppate:

Group Rows

Come si vede, la riga 2 in colonna C ha il totale delle righe sottostanti (i comuni della provincia di Alessandria) e così via per tutte le province della regione Piemonte e le diverse regioni d’Italia. Insomma, certo non passo il mio tempo a selezionare e raggruppare manualmente migliaia di righe!

Meglio scrivere una macro che posso poi riutilizzare :-) e ottenere il risultato voluto:

GroupedRows

Nella finestra di Visual Basic in un modulo inserisco il seguente codice:

Sub sOutlineGrouping()
Dim rngCurrent As Range ' current range
Dim strPrevValue As String ' previous value
Dim lngStartRow As Long ' starting row of the grouping
Dim lngEndRow As Long ' ending row of the grouping

Range("A2").ClearOutline ' if grouping already exists, remove it
Range("A2").CurrentRegion.Rows.Hidden = False ' show all rows, if any hidden

Set rngCurrent = Range("A2") ' starting cell to create grouping
Do While Not rngCurrent = "" ' until the cell is not empty, so the loop stops at the end of data
 If rngCurrent <> strPrevValue Then ' if range is different from previous value, it means grouping label has changed, so set the new starting row
      lngStartRow = rngCurrent.Row + 1 ' the starting row must be incremented by 1, because to group data you must exclude the first row
 End If
 strPrevValue = rngCurrent ' store the current value in strPrevValue variable
 Set rngCurrent = rngCurrent.Offset(1) ' move to next row
 If rngCurrent <> strPrevValue Then ' if next row value is different from previous one, then it is time to group rows
      lngEndRow = rngCurrent.Offset(-1).Row ' set ending row, moving back one row
      Rows(lngStartRow & ":" & lngEndRow).Group ' finally, group rows
 End If
Loop ' restart the loop
End Sub

In estrema sintesi, mi posiziono sulla cella A2 e scorro le righe finché la cella A2 contiene dati, controllando il valore che trovo in colonna A. Quando il valore cambia rispetto al precedente, significa che è iniziato un nuovo gruppo di righe, perciò devo raggruppare le precedenti.