Excel User Group
Microsoft Excel blogs, forums, files. Read, ask questions, provide answers.

Macro-Insert Row below each Subtotal

Latest post Sun, Apr 20 2008 1:35 AM by blue_sphinx. 16 replies.
  • Thu, Apr 3 2008 3:31 AM

    • blue_sphinx
    • Top 25 Contributor
    • Joined on Thu, Mar 27 2008
    • Phils/UAE
    • Posts 26
    • Points 434

    Macro-Insert Row below each Subtotal

    Hi All,

     Please help. After I subtotal my data using Macro how can I insert rows below each subtotal.

    Example:

    Range("A5:AG61").Select
        Selection.Subtotal GroupBy:=5, Function:=xlSum, TotalList:=Array(8, 9, 10, 11, _
            15, 16, 17, 18, 20, 21, 22, 23, 29, 30, 31, 32), Replace:=True, PageBreaks:= _
            False, SummaryBelowData:=True

    Big Thanks!

    Blue

    • Post Points: 21
  • Thu, Apr 3 2008 8:41 AM In reply to

    • Pgmer
    • Top 50 Contributor
    • Joined on Mon, Mar 31 2008
    • Posts 8
    • Points 136

    Re: Macro-Insert Row below each Subtotal

    The easiest way is to do something like this:

        Rows("62:64").Select
        Selection.Insert Shift:=xlDown

    This would insert three rows below the subtotal at row 61.  It will move any data in rows 62 through 64 down.

    Pgmer

     I let my mind wander ... it never came back!

    Filed under:
    • Post Points: 21
  • Thu, Apr 3 2008 9:04 AM In reply to

    • Alex J
    • Top 25 Contributor
    • Joined on Wed, Jan 9 2008
    • Posts 21
    • Points 349

    Re: Macro-Insert Row below each Subtotal

    You would be better with:

    Rows("62:64").Insert Shift:=xlDown

    No selection works better (ref Walkenback VBA Power Programming)

    Regards, Alex J

    • Post Points: 21
  • Tue, Apr 8 2008 6:35 AM In reply to

    • blue_sphinx
    • Top 25 Contributor
    • Joined on Thu, Mar 27 2008
    • Phils/UAE
    • Posts 26
    • Points 434

    Re: Macro-Insert Row below each Subtotal

    Hmm Hi again!

    What if I have hundreds subtotal. I think its not efficient to do it manually. This could only be applicable for fewer subtotals.Currently, I have 13 departments which needed to do subtotals(in one sheet), 130 groups which also need to be subtotals(another worksheets), and 570 subgroups which also need to subtotals(another worksheets). Is there any way that we could add row below each subtotal with this amount of information?

    Big Thanks.

    • Post Points: 21
  • Tue, Apr 8 2008 8:16 AM In reply to

    Re: Macro-Insert Row below each Subtotal

    Blue,

    I think this might do what you need it to.

    Option Explicit

    '---------------------------------------------------------------------------------------
    ' Procedure : Insert_Rows_Below_SubTotals
    ' Author    : David Badilotti
    ' Date      : 4/8/2008
    ' Purpose   : Inserts a user determined number of rows below each subtotal in the
    '             selected range
    '---------------------------------------------------------------------------------------
    '

    Public Sub Insert_Rows_Below_SubTotals()

    '======================================================================================================================
    '   Declarations
    '======================================================================================================================
    '**********************************************************************************************************************
    '   Variable Declarations
    '**********************************************************************************************************************

    'Ranges
    Dim rngSubtotals As Range
    Dim c As Range

    'Temps
    Dim lngRowsToInsert As Long


    '======================================================================================================================
    '   Code
    '======================================================================================================================

    'Get the number of Rows to Insert from the user
    lngRowsToInsert = Application.InputBox("How many Rows do you want to insert below each subtotal?", _
      "Number of Rows", 1)

    'Get the range containing subtotals
    Set rngSubtotals = Application.InputBox("Select the range containing the subtotals", _
      "Range Selection", Type:=8)

    'Loop through range looking for the word "Total"
    For Each c In rngSubtotals
      If Right(c.Value, 5) = "Total" Then
          c.Offset(1, 0).EntireRow.Resize(lngRowsToInsert).Insert shift:=xlDown
      Else
      End If
    Next c

    '======================================================================================================================
    '   Clean Up
    '======================================================================================================================

    Set rngSubtotals = Nothing
    Set c = Nothing


    End Sub

    David B.

    • Post Points: 21
  • Wed, Apr 9 2008 1:19 AM In reply to

    • blue_sphinx
    • Top 25 Contributor
    • Joined on Thu, Mar 27 2008
    • Phils/UAE
    • Posts 26
    • Points 434

    Re: Macro-Insert Row below each Subtotal

    Hi David, 

    YesBig Smile I just paste the code and hey its working! Yipeee!

    Thanks a lot.

    • Post Points: 5
  • Thu, Apr 10 2008 1:37 AM In reply to

    • blue_sphinx
    • Top 25 Contributor
    • Joined on Thu, Mar 27 2008
    • Phils/UAE
    • Posts 26
    • Points 434

    Re: Macro-Insert Row below each Subtotal

    Hi David,

    Is there any way that we could just locate automatically those rows which has subtotal?

    What if I have hundreds of subtotal, Is it possible to macro to just lookup those with cell contains total (like in your msgbox question(second step))?

    Big thanks.

    Blue

    • Post Points: 21
  • Thu, Apr 10 2008 8:25 AM In reply to

    Re: Macro-Insert Row below each Subtotal

    Blue,

    Do you mean have the macro just look through the sheet?  If so, that's entirely possible.  The only concern would be that you might have something ending in 'Total' elsewhere on the sheet.  That's why I built it so you could select the column(s) with the subtotals.

    You'd probably want it to limit it to the used range.  I just ran the existing macro on one of my own workbooks, and selected the entire worksheet rather than just the column containing the subtotal labels.  It took 48 seconds to run.

    If you want to try that, simply change the line of code with the InputBox allowing range selection to Set rngSubtotals = ActiveSheet.UsedRange

    Let me know if that works for you.

    David B.

    • Post Points: 21
  • Thu, Apr 10 2008 9:06 AM In reply to

    • blue_sphinx
    • Top 25 Contributor
    • Joined on Thu, Mar 27 2008
    • Phils/UAE
    • Posts 26
    • Points 434

    Re: Macro-Insert Row below each Subtotal

    Hi David, 

    YesBig Smile It works. Yipeeeeeeeeeee!!!!!!!!!!!!!

    Thank you so much(again)....

    Blue

     

    • Post Points: 5
  • Sun, Apr 13 2008 4:25 AM In reply to

    • blue_sphinx
    • Top 25 Contributor
    • Joined on Thu, Mar 27 2008
    • Phils/UAE
    • Posts 26
    • Points 434

    Re: Macro-Insert Row below each Subtotal

    Hi David,

    I know this could be too much but this will be the last inquiry that I'll ask for this topic. My apology this is due to huge amount of information..

    The macro you provide is currently working but I would like to add (1)if it possible also to put header for each summary report subtotal? and (2)if it possible to put borderline for each summary report subtotal?

    Example:

    Number of Rows to be insert after the subtotal: 2

    The Row 3 will be paste for the Header.

    Take note that header is copied only on same sheet Rows("3:4")

    The Borderline is range per header to range of subtotal.

    Big Thanks.

    Blue

     

    • Post Points: 21
  • Mon, Apr 14 2008 7:59 AM In reply to

    Re: Macro-Insert Row below each Subtotal

    Blue,

    Before I get started, I just want to be sure I understand what you're looking for.  If I understand your desire, you are attempting to format each subtotaled section of your report to make it a bit more distinctive.  You want your column headers repeated before each section, and you want the entire section bounded by a border.  I've done a mockup table below.  See if it appears to reflect what you're looking for (Borders would encompasse the header to the subtotal (I wasn't willing to write the HTML to put them in.  I'm lazy Smile.)).

     

    Location

    Division

    Team

    Revenue

    Profits

    Winnipeg, MB

    Widgets

    Green

    $9,987.38

    $134.37

    Red

    $16,844.74

    $1,181.17

    Orange

    $74.35

    $0.00

    Blue

    $10,620.51

    $605.65

    Thingamabobs

    White

    $5,125.30

    $586.16

    Doohickies

    Black

    $3,539.20

    $175.82

    Winnipeg, MB Total

     

     

    $46,191.49

    $2,683.19

     

     

     

     

     

    Location

    Division

    Team

    Revenue

    Profits

    Regina, SK

    Widgets

    Bombers

    $2,539.22

    $63.17

    Thingamabobs

    Tigercats

    $635.62

    $0.00

    Doohickies

    Roughriders

    $1,139.87

    $41.70

    Argonauts

    $600.31

    $0.21

    Lions

    $3,213.80

    $325.27

    Eskimos

    $13.16

    $4.03

    Whatchamacallits

    Stampeders

    $68.27

    $4.59

    Regina, SK Total

     

     

    $8,210.25

    $438.97

     

    David B.

    • Post Points: 21
  • Mon, Apr 14 2008 9:25 AM In reply to

    • blue_sphinx
    • Top 25 Contributor
    • Joined on Thu, Mar 27 2008
    • Phils/UAE
    • Posts 26
    • Points 434

    Re: Macro-Insert Row below each Subtotal

    Hi David,

    YesYou got my point!

    (Don't worry there will be no pressure to your lazinessWink ...kidding)

    Please help....Big Thanks.

    Blue

    • Post Points: 5
  • Thu, Apr 17 2008 6:44 AM In reply to

    • blue_sphinx
    • Top 25 Contributor
    • Joined on Thu, Mar 27 2008
    • Phils/UAE
    • Posts 26
    • Points 434

    Re: Macro-Insert Row below each Subtotal

    Hi David,

     Good news..I already figure out inserting the header for each subtotal. Big Smile

    'Loop through range looking for the word "Total"
    For Each c In rngSubtotals
     If Right(c.Value, 5) = "Total" Then
          Rows("37:38").Copy Yes
          c.Offset(1).EntireRow.Insert Yes
          c.Offset(1, 0).EntireRow.Resize(lngRowsToInsert).Insert shift:=xlDown

    Yes I just add this data and it works!

    Thanks for the help!

    Blue

     

    • Post Points: 21
  • Thu, Apr 17 2008 8:03 AM In reply to

    Re: Macro-Insert Row below each Subtotal

    Blue,

    Glad you found a solution.  I'm afraid I was getting a bit too ambitious.  I was going for 'can be used anywhere' rather than just a solution to your existing situation.  And I've only had a few minutes before work to pick at it.

    Here's what I came up with.

    Public Sub Insert_Rows_Below_SubTotals()

    '======================================================================================================================
    '   Declarations
    '======================================================================================================================
    '**********************************************************************************************************************
    '   Variable Declarations
    '**********************************************************************************************************************
    'Booleans
    Dim bolFound As Boolean

    'Counters
    Dim lngCount1                           As Long

    'Ranges
    Dim rngSubTotals                       As Range
    Dim rngHeaders                          As Range
    Dim c                                   As Range
    Dim c1 As Range
    Dim rngSubTotalSection As Range

    'Temps
    Dim lngRowsToInsert                     As Long
    Dim bytStartColumn                      As Byte
    Dim bytEndColumn                        As Byte
    Dim bytTotalsColumn As Byte
    Dim lngStartRow                         As Long
    Dim lngEndRow                           As Long

    '======================================================================================================================
    '   Code
    '======================================================================================================================

    'Get the number of Rows to Insert from the user
    lngRowsToInsert = _
        Application.InputBox("How many Rows do you want to insert below each subtotal?", _
        "Number of Rows", 1)

    'Find the column with the 'Totals'

    With ActiveSheet.UsedRange
      Set c = .Find(What:="Total", LookIn:=xlValues, LookAt:=xlPart)
     
      bolFound = False
      While Not bolFound
        If Not c Is Nothing Then
          If Right(c.Value, 5) = "Total" Then
            bytTotalsColumn = c.Column
            bolFound = True
          Else
            Set c1 = .FindNext(c)
              If Not c1 Is Nothing Then
                Set c = c1
              Else
                MsgBox "No totals found"
                Exit Sub
              End If
          End If
        Else
          MsgBox "No totals found"
          Exit Sub
        End If
      Wend
    End With

    'Set the SubtTotals Range
    With ActiveSheet
      Set rngSubTotals = .Range(.Cells(.UsedRange.Row, bytTotalsColumn), _
          .Cells((.UsedRange.Row + .UsedRange.Rows.Count - 1), bytTotalsColumn))
     
    End With

    'Get the Header range from the user
    Set rngHeaders = _
        Application.InputBox("Select the Headers to be repeated for each SubTotal Range", _
        "User Input Required", Type:=8)

    'Assuming the header range encompasses the columns to be formatted, set the left and right columns
    'for the formatting.
    bytStartColumn = rngHeaders.Column
    bytEndColumn = bytStartColumn + rngHeaders.Columns.Count - 1

    'Loop through range looking for the word "Total"
    For Each c In ActiveSheet.UsedRange
      If Right(c.Value, 5) = "Total" Then
        c.Offset(1, 0).EntireRow.Resize(lngRowsToInsert).Insert shift:=xlDown
      Else
      End If
    Next c


    rngHeaders.Copy

    'Set Headers
    For Each c In ActiveSheet.UsedRange
      If Right(c.Value, 5) = "Total" Then
        c.Offset(lngRowsToInsert, lngStartRow).PasteSpecial xlPasteAll
      Else
      End If
    Next c


    'Get the start of the first section
    lngStartRow = rngHeaders.Row

    'Find the first Total to identify the end of the range
    With rngSubTotals
      Set c = .Find(What:="Total", LookIn:=xlValues, LookAt:=xlPart)

      If Not c Is Nothing Then
      Else
        MsgBox "Couldn't find the end of the section."
        Exit Sub
      End If
     
      Set c1 = c

      Do
       
        'Create section to format
        With ActiveSheet
          Set rngSubTotalSection = .Range(.Cells(lngStartRow, bytStartColumn), _
              .Cells(c1.Row, bytEndColumn))
        End With
       
        'Format section
        With rngSubTotalSection.Borders(xlEdgeLeft)
          .LineStyle = xlContinuous
          .Weight = xlThick
          .ColorIndex = 47
        End With
        With rngSubTotalSection.Borders(xlEdgeTop)
          .LineStyle = xlContinuous
          .Weight = xlThick
          .ColorIndex = 47
        End With
        With rngSubTotalSection.Borders(xlEdgeBottom)
          .LineStyle = xlContinuous
          .Weight = xlThick
          .ColorIndex = 47
        End With
        With rngSubTotalSection.Borders(xlEdgeRight)
          .LineStyle = xlContinuous
          .Weight = xlThick
          .ColorIndex = 47
        End With
       
        lngStartRow = c1.Row + lngRowsToInsert
        Set c1 = .FindNext(c1)
     
      Loop Until c1.Address = c.Address

     

    End With

    '======================================================================================================================
    '   Clean Up
    '======================================================================================================================

    Set rngSubTotals = Nothing
    Set rngHeaders = Nothing
    Set c = Nothing
    Set c1 = Nothing
    Set rngSubTotalSection = Nothing

     

    End Sub

     

    This should handle your formatting requirement.  Note that if you want different formatting, you can simply record formatting one of the sections the way you want it, and then use that to replace the formatting code I've got.

    Sorry again for the delay

    David B.

    • Post Points: 21
  • Thu, Apr 17 2008 8:34 AM In reply to

    • blue_sphinx
    • Top 25 Contributor
    • Joined on Thu, Mar 27 2008
    • Phils/UAE
    • Posts 26
    • Points 434

    Re: Macro-Insert Row below each Subtotal

    Hi David,

    I understand. I've see that all of you are in the SUMMIT right now thats why your "too much" busy.

    When I'm running  it some of the data is being removed and can you please help me on the borders.

    Also, the header that supposedly placed in A column was located in E column.

    Am I running it wrongly? Please advise.

    Big Thanks.

    Blue

    • Post Points: 21
Page 1 of 2 (17 items) 1 2 Next > | RSS
Copyright Excel User Group and the relevant contributors, 2008. All Trade Marks acknowledged. This site is a peer-to-peer site and NOT affiliated in any way to Microsoft Corp. All rights reserved.