In VSTO 2010 in Excel, the Range.Sort method doesn’t seem to work for me. Here’s my example code. It puts the numbers 1 to 20 in reverse order in column A, and then unsuccessfully tries to sort them.
Worksheet sheet = Globals.ThisAddIn.Application.ActiveSheet;
Enumerable.Range(1, 20).ToList().ForEach(i => sheet.Cells[21 - i, 1] = i);
sheet.Columns[1].Sort();
According to the documentation, the Sort with no arguments will sort in ascending order. Just in case I tried specifying Order1: XlSortOrder.xlAscending.
I also tried
sheet.Columns[1].Select().Sort();
to select the column first, but this didn’t work either.
How can I sort a Range of cells?
I tried your approach in VBA and receved the error “sort method of range class failed”.
I resolved that by passing the range as the “Key1” argument of the method. Seems redundant, but it works. Here’s your sample code with the same fix applied: