I have two cases. The preliminary code:
open Microsoft.Office.Interop.Excel
let xl = ApplicationClass()
xl.Workbooks.OpenText(fileName...)
let wb = xl.Workbooks.Item(1)
let ws = wb.ActiveSheet :?> Worksheet
let rows = string ws.UsedRange.Rows.Count
First, I try the following to sort:
ws.Sort.SortFields.Clear()
ws.Sort.SortFields.Add(xl.Range("A8:A" + rows), XlSortOn.xlSortOnValues, XlSortOrder.xlAscending, XlSortDataOption.xlSortNormal) |> ignore
ws.Sort.SortFields.Add(xl.Range("H8:H" + rows), XlSortOn.xlSortOnValues, XlSortOrder.xlAscending, XlSortDataOption.xlSortNormal) |> ignore
ws.Sort.SetRange(xl.Range("A7:I" + rows))
ws.Sort.Header <- XlYesNoGuess.xlYes
ws.Sort.MatchCase <- false
ws.Sort.Orientation <- XlSortOrientation.xlSortRows
ws.Sort.SortMethod <- XlSortMethod.xlPinYin
ws.Sort.Apply()
This results in “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.”.
Then I try the following to sort:
ws.Range("A7:I" + rows).Sort(xl.Range("A8:A" + rows), XlSortOrder.xlAscending,
xl.Range("H8:H" + rows), "", XlSortOrder.xlAscending,
"", XlSortOrder.xlAscending, XlYesNoGuess.xlYes,
XlSortOrientation.xlSortRows) |> ignore
This results in my columns being rearranged, though I don’t see any logic to the rearrangement. And the rows are not sorted.
Please tell me what I’m doing wrong.
I haven’t figured out why the first Sort attempt doesn’t work. But I checked out the documentation on the second Sort. Using named parameters and dropping all but necessary parameters, I came up with the following:
The default Orientation is xlSortRows. I interpret this as sorting the rows, the normal, default, intuitive sort that Excel does when one sorts manually. Oh no. If you want the normal, default, intuitive sort that Excel does when one sorts manually, specify xlSortColumns.