You are here:

Excel/VBA Sorting Table by certain column excluding last row



tested it, but i get a runtime error 9, subscript out of range. when i debug, the highlighted row is:

"With ActiveWorkbook.Worksheets("Sheet1 (2)").Sort"

from what i can understand, this is should run through any sheet, regardless of the name? if not, i need it to run through specific sheets, as mine are named, and i would like to enter these specific names.

it did work, however, when i changed ("Sheet1 (2)") to ("ActualSheetName"), but only on that sheet. i tried entering a second name in the iteration but it did not work.

otherwise, once changed the name to ("ActualSheetName") it worked beautifully.

so, with this last tweak, it should work just fine. i am in a world of debt!!!


I just forgot to edit that line of code to point it to the activesheet:

Sub SortSubtotals()
  Dim r As Range
  Set r = ActiveCell.CurrentRegion
  Set r = r.Offset(2).Resize(r.Rows.Count - 2, 24)
  ActiveSheet.Outline.ShowLevels RowLevels:=2
  ActiveSheet.Sort.SortFields.Add Key:=Range( _
      "O4"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:= _
  With Activesheet.Sort  ' <== corrected
      .SetRange r
      .Header = xlYes
      .MatchCase = False
      .Orientation = xlTopToBottom
      .SortMethod = xlPinYin
  End With
  ActiveSheet.Outline.ShowLevels RowLevels:=3
End Sub

sorry for the oversight.  It should run on the activesheet as long as that sheet fits the assumptions stated.

Tom Ogilvy

About Excel
This topic answers questions related to Microsoft Excel spreadsheet (or workbook) stand-alone or Mircrosoft Office Excel including Excel 2003, Excel 2007, Office 2000, and Office XP. You can get Excel help on Excel formulas(or functions), Excell macros, charting in Excel, advanced features, and the general use of Excel. This does not provide a general Excel tutorial nor the basics of using a spreadsheet. It provides specific answers to using Microsoft Excel only. If you do not see your Excel question answered in this area then please ask an Excel question here


All Answers

Answers by Expert:

Ask Experts


Tom Ogilvy


Selected as an Excel MVP by Microsoft since 1999. Answering Excel questions in Allexperts since its inception in 2001. Able to answer questions on almost all aspects of Excel's internal capabilities. If seeking a VBA solution, please specify that in your question itself so I give you the answer you want. [Excel has weak protection - if you are distributing an application, I don't answer questions on how to protect your project from your users.]


Extensive experience.

Master of Science (MS) degree Operations Research (ORSA)

Awards and Honors
Microsoft MVP in Excel.

©2017 All rights reserved.