This documentation is archived and is not being maintained.

How to: Sort Data in Worksheets Programmatically

Updated: July 2008

Applies to

The information in this topic applies only to the specified Visual Studio Tools for Office projects and versions of Microsoft Office.

Project type

  • Document-level projects

  • Application-level projects

Microsoft Office version

  • Excel 2003

  • Excel 2007

For more information, see Features Available by Application and Project Type.

You can sort data that is contained in worksheet ranges and lists at run time. The following code sorts a multi-column range named Fruits by the data in the first column, and then by the data in the second column.

Starting in Visual Studio 2008 Service Pack 1 (SP1), you can sort data at run time in application-level add-ins.

To sort data in a NamedRange control

  • Call the Sort method of the NamedRange control. The following example requires a NamedRange control named Fruits on a worksheet. This code must be placed in a sheet class, not in the ThisWorkbook class.

        this.Fruits.Columns[1, missing], Excel.XlSortOrder.xlAscending,
        this.Fruits.Columns[2, missing], missing, Excel.XlSortOrder.xlAscending,
        missing, Excel.XlSortOrder.xlAscending,
        Excel.XlYesNoGuess.xlNo, missing, missing, 

Place the following code in Sheet1.vb or Sheet1.cs to sort data in a ListObject control. The code assumes that you have a Microsoft.Office.Tools.Excel.ListObject control named fruitList in a worksheet named Sheet1.

To sort data in a ListObject control

To sort data in a native range

To sort data in a ListObject control




July 2008

Added a code example that can be used in an application-level add-in.

Customer feedback.