Grouping in VB

davidhall80

Well-known Member
Joined
Jul 8, 2006
Messages
663
I have two Total columns. Because this is moving data, I never know which two columns the total columns are in. I need to group the data between the columns. The first column heading is "YTD" and the second column heading is "Monthly". The column headings begin in row 10.
 

Excel Facts

Save Often
If you start asking yourself if now is a good time to save your Excel workbook, the answer is Yes

Damon Ostrander

MrExcel MVP
Joined
Feb 17, 2002
Messages
4,239
Hi david,

You mentioned that the column headings "start in row 10", implying that they might end in a different row. Assuming that you meant "are in row 10" and you want the YTD and Monthly columns to be included in the group, the following code should do it:

Code:
Sub GroupTotalColumns()
   'Groups columns starting with YTD and ending with Monthly in row 10
   Dim iCol    As Integer
   Dim iCol1   As Integer
   Dim iCol2   As Integer
   iCol1 = 0
   
   For iCol = 1 To Cells(10, 256).End(xlToLeft).Column
      If iCol1 = 0 Then
         If Cells(10, iCol).Value = "YTD" Then iCol1 = iCol
      Else
         If Cells(10, iCol).Value = "Monthly" Then
            iCol2 = iCol
            GoTo FoundGroup
         End If
      End If
   Next iCol
   MsgBox IIf(iCol1 = 0, "YTD", "monthly") & " header not found.", vbExclamation, "Can't group columns"
   Exit Sub
   
FoundGroup:
   Range(Columns(iCol1), Columns(iCol2)).Group
   
End Sub

Keep Excelling.

Damon
 
Master Excel Bundle

Excel contains over 450 functions, with more added every year. That’s a huge number, so where should you start? Right here with this bundle.

Forum statistics

Threads
1,167,836
Messages
5,855,912
Members
431,774
Latest member
WillWilco

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Top