简体   繁体   English

C# Excel 范围排序

[英]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 工作簿中的第 3 行)包含需要按升序从左到右排序的列标题:

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'.这当前会生成错误“范围 class 的排序方法失败”。

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:等效的 VBA 工作正常:

 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.我将 Range 作为第一个参数并将 Orientation 设置为 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/ http://social.msdn.microsoft.com/Forums/en-US/exceldev/thread/a699d754-98d5-4241-87da-8761c520ba72/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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