简体   繁体   中英

Sorting on cell color in Excel using C#

My code crashes with the error message - "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."

I'm trying to sort on cell color. This is my code:

_wks.Sort.SortFields.Clear();
_wks.Sort.SortFields.Add(
    DupesColumn, 
    XlSortOn.xlSortOnCellColor,
    XlSortOrder.xlAscending);
_wks.Sort.SortFields[1].SortOnValue.Color = XlRgbColor.rgbRoyalBlue;

_wks.Sort.SetRange(DupesColumn.CurrentRegion);
_wks.Sort.Header = XlYesNoGuess.xlYes;
_wks.Sort.MatchCase = false;
_wks.Sort.Orientation = XlSortOrientation.xlSortRows;
_wks.Sort.SortMethod = XlSortMethod.xlPinYin;
_wks.Sort.Apply();

DupesColumn is a range. I'm using VS 2013. I tried defining the range as dynamic, didn't work.

Any ideas?

I think your code is breaking on line:

_wks.Sort.SortFields[1].SortOnValue.Color = XlRgbColor.rgbRoyalBlue;

This will be because the reference to SortFields[1] is not valid as it's zero based. Therefore if you've cleared the SortFields and then added only one to it then it's reference will be 0 not 1. So the following should work:

_wks.Sort.SortFields[0].SortOnValue.Color = XlRgbColor.rgbRoyalBlue;

It's because of Orientation property's value that you set.

This line

_wks.Sort.Orientation = XlSortOrientation.xlSortRows;

should be

_wks.Sort.Orientation = XlSortOrientation.xlSortColumns;


Further reading:
1) F# Excel Range.Sort Fails or Rearranges Columns

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