Hello, I'm looking for vba that can automatically apply grouping to a data set (that is current just a list with no grouping at all) as shown in first image- my issue is that my actual data set is hundreds of lines long and doing manually is very time consuming.
I have tried the following code but it ends up just grouping everything by BUD a per screenshot 2
Sub GroupByMag2()
Dim ws As Worksheet
Dim lastRow As Long
Dim i As Long
Dim groupStart As Long
' Set the worksheet to work with
Set ws = ThisWorkbook.Sheets("Sheet1") ' Change "Sheet1" to your actual sheet name
' Find the last row with data in column A
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
groupStart = 0 ' Initialize the group start
' Loop through each row in column A
For i = 1 To lastRow + 1
' Check if the cell contains "mag"
If i <= lastRow And InStr(1, ws.Cells(i, "A").Value, "mag", vbTextCompare) > 0 Then
If groupStart > 0 Then
' End the previous group before starting the new one
ws.Rows(groupStart & ":" & i - 1).Group
End If
' Start a new group from the current "mag" row
groupStart = i
ElseIf i > lastRow And groupStart > 0 Then
' At the end of data, group the last set of rows
ws.Rows(groupStart & ":" & lastRow).Group
End If
Next i
' Optionally, expand all groups to level 1
ws.Outline.ShowLevels RowLevels:=1
End Sub
I have tried the following code but it ends up just grouping everything by BUD a per screenshot 2
Sub GroupByMag2()
Dim ws As Worksheet
Dim lastRow As Long
Dim i As Long
Dim groupStart As Long
' Set the worksheet to work with
Set ws = ThisWorkbook.Sheets("Sheet1") ' Change "Sheet1" to your actual sheet name
' Find the last row with data in column A
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
groupStart = 0 ' Initialize the group start
' Loop through each row in column A
For i = 1 To lastRow + 1
' Check if the cell contains "mag"
If i <= lastRow And InStr(1, ws.Cells(i, "A").Value, "mag", vbTextCompare) > 0 Then
If groupStart > 0 Then
' End the previous group before starting the new one
ws.Rows(groupStart & ":" & i - 1).Group
End If
' Start a new group from the current "mag" row
groupStart = i
ElseIf i > lastRow And groupStart > 0 Then
' At the end of data, group the last set of rows
ws.Rows(groupStart & ":" & lastRow).Group
End If
Next i
' Optionally, expand all groups to level 1
ws.Outline.ShowLevels RowLevels:=1
End Sub