3

我有两个案例。初步代码:

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

首先,我尝试以下排序:

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()

这会导致“排序引用无效。请确保它在您要排序的数据内,并且第一个排序依据框不同或空白。”。

然后我尝试以下排序:

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

这导致我的列被重新排列,尽管我没有看到重新排列的任何逻辑。并且行没有排序。

请告诉我我做错了什么。

4

2 回答 2

3

我还没弄清楚为什么第一次排序尝试不起作用。但我查看了第二次排序的文档。使用命名参数并删除除必要参数之外的所有参数,我想出了以下内容:

ws.Range("A8:H" + rows).Sort(Key1=xl.Range("A8:A" + rows), Key2=xl.Range("H8:H" + rows),
                             Orientation=XlSortOrientation.xlSortColumns) |> ignore

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.

于 2012-10-25T14:22:52.440 回答
1

The first Sort doesn't work because you're probably trying to sort a table (judging by property Header set to XlYesNoGuess.xlYes) by columns located on A and H. In this case you can only sort using "Sort top to bottom"(xlSortColumns).

You can also convince yourself by trying this in Excel first and see what options are available:
1) Select the range you want to apply sorting (e.g. in your case "A7:I" + rows)
2) Click on "Data" menu -> "Sort & Filter" task pane -> Sort
3) Add/Delete columns/rows by using "Add Level"/"Delete Level" buttons
4) Then you can select whatever level you want and click "Options..." button and you will see your available "Sort Options".
You will notice that in case of a table you will have only one available option for "Orientation", which is "Sort top to bottom"

xlSortColumns - sorts by columns (meaning rows are sorted based on those columns)

xlSortRows - sort by rows (meaning columns are sorted based on those rows)

于 2016-08-25T12:06:12.590 回答