Export (0) Print
Expand All
Expand Minimize
2 out of 2 rated this helpful - Rate this topic

How to: Sort Data in Worksheets Programmatically

NoteNote

Some code examples in this topic use the this or Me keyword or the Globals class in a way that is specific to document-level customizations, or they rely on features of document-level customizations such as host controls. These examples can be compiled only if you have the required applications installed. For more information, see Features Available by Product Combination.

Use the Sort method of the NamedRange object to sort data in a worksheet.

You can sort data that is contained in worksheet ranges and lists. Place the following code in a worksheet to sort a multi-column range named Fruits by the data in the first column, and then by the data in the second column. This code example assumes that you have a NamedRange control named Fruits on a worksheet.

To sort data in a NamedRange control

  • Call the Sort method of the NamedRange control.

    this.Fruits.Sort(
        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, 
        Excel.XlSortOrientation.xlSortColumns,
        Excel.XlSortMethod.xlPinYin,
        Excel.XlSortDataOption.xlSortNormal,
        Excel.XlSortDataOption.xlSortNormal,
        Excel.XlSortDataOption.xlSortNormal); 
    
    

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

To sort data in a ListObject control

  • Call the Sort method of the Range property of the ListObject host control.

    this.fruitList.Range.Sort(
        this.fruitList.ListColumns[1].Range, Excel.XlSortOrder.xlAscending,
        this.fruitList.ListColumns[2].Range, missing, Excel.XlSortOrder.xlAscending,
        missing, Excel.XlSortOrder.xlAscending, 
        Excel.XlYesNoGuess.xlYes, missing, missing, 
        Excel.XlSortOrientation.xlSortColumns,
        Excel.XlSortMethod.xlPinYin, 
        Excel.XlSortDataOption.xlSortNormal,
        Excel.XlSortDataOption.xlSortNormal,
        Excel.XlSortDataOption.xlSortNormal);
    
    

Robust Programming

  • The named range code example requires that a NamedRange control, named Fruits, exist on a worksheet.

  • The list code example requires that a ListObject control, named fruitList, exist on a worksheet.

  • This code must be placed in a sheet class, not in the ThisWorkbook class.

See Also

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.