简体   繁体   中英

C# Excel Range Sort

I would like to sort a range. The first row (Row 3 in the Excel workbook) contains the column headers, which need sorted, left to right, in ascending order:

Excel.Range tempRange = ws.get_Range("F3", "H8");

tempRange.Sort(Type.Missing,
                    Excel.XlSortOrder.xlAscending,
                    Type.Missing,
                    Excel.XlSortOrder.xlAscending,
                    Excel.XlSortOrder.xlAscending,
                    Type.Missing,
                    Excel.XlSortOrder.xlAscending,
                    Excel.XlYesNoGuess.xlYes,
                    Type.Missing,
                    Type.Missing,
                    Excel.XlSortOrientation.xlSortColumns,
                    Excel.XlSortMethod.xlPinYin,
                    Excel.XlSortDataOption.xlSortNormal,
                    Excel.XlSortDataOption.xlSortNormal,
                    Excel.XlSortDataOption.xlSortNormal);

This currently generates the error 'Sort method of Range class failed'.

I've tried various parameters at the start of the sort method, but this generates the 'The sort reference is not valid. Make sure that it's within the data you want to sort, and the first Sort By box isn't the same or blank' error message.

Where am I going wrong?

The equivalent VBA Works fine:

 With ActiveWorkbook.Worksheets("Sheet1").Sort
    .SetRange Range("F3:H8")
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlLeftToRight
    .SortMethod = xlPinYin
    .Apply
End With

Thanks very much

Joe

I stated the Range as the first parameter & set the Orientation to Excel.XlSortOrientation.xlSortRows.

                tempRange.Sort(tempRange,
                    Excel.XlSortOrder.xlAscending,
                    Type.Missing, Type.Missing,
                    Excel.XlSortOrder.xlAscending,
                    Type.Missing,
                    Excel.XlSortOrder.xlAscending,
                    Excel.XlYesNoGuess.xlYes, 
                    Type.Missing,
                    Type.Missing,
                    Excel.XlSortOrientation.xlSortRows,
                    Excel.XlSortMethod.xlPinYin,
                    Excel.XlSortDataOption.xlSortNormal,
                    Excel.XlSortDataOption.xlSortNormal,
                    Excel.XlSortDataOption.xlSortNormal);

Useful link:

http://social.msdn.microsoft.com/Forums/en-US/exceldev/thread/a699d754-98d5-4241-87da-8761c520ba72/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM