C#Excel范围排序

时间:2011-07-15 12:05:18

标签: c# excel-vba vba excel

我想对一个范围进行排序。第一行(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);

这当前生成错误'Range类的排序方法失败'。

我在sort方法的开头尝试了各种参数,但这会生成'排序参考无效。确保它在您要排序的数据中,并且第一个“排序依据”框不相同或为空“错误消息。

我哪里错了?

等效的VBA工作正常:

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

非常感谢

1 个答案:

答案 0 :(得分:1)

我将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);

有用的链接:

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

相关问题