vba Excel SortFields 添加然后排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24352229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 03:33:31  来源:igfitidea点击:

Excel SortFields add then sort

excelvbasortingexcel-vbarange

提问by kiriloff

Would you help me understand this snippset:

你能帮我理解这个片段吗:

First, it seems that a sorting rule is added with

首先,似乎添加了一个排序规则

MainSheet.Sort.SortFields.Clear
For lI = 1 To vSortKeys(0, 1)   
    MainSheet.Sort.SortFields.Add Key:=Range(vSortKeys(lI, 1) & 2), 
       SortOn:=xlSortOnValues, Order:=vSortKeys(lI, 2), DataOption:=xlSortNormal
Next

Then, I understand that the following code is effectively running the sort

然后,我了解到以下代码有效地运行了排序

With MainSheet.Sort
    .SetRange Range("A" & lFrom & ":" & GEN_REV_END & lTo)
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

Is this interpretation correct - need to add a sorting rule first, then apply it with the second part ?

这种解释是否正确 - 需要先添加排序规则,然后将其应用于第二部分?

Then, why are we defining a range for sort in the second part, in

那么,为什么我们要在第二部分定义一个排序范围,在

With MainSheet.Sort
    .SetRange Range("A" & lFrom & ":" & GEN_REV_END & lTo)

End With

Is it not already in the rule that we sort for Key:=Range(vSortKeys(lI, 1) & 2)? On which range of cells is the sort effectively run ?

它不是已经在我们排序的规则中了Key:=Range(vSortKeys(lI, 1) & 2)吗?排序在哪个单元格范围内有效运行?

回答by Kapol

The sorting is being applied to the range specified in Sort.SetRange. The Keyparameter in Sort.SortFields.Addallows you to specify fields that will determine the order of soring. Each field can be just the cell with the column header. You can add multiple keys for several sorting levels.

排序将应用于 中指定的范围Sort.SetRange。该Key参数Sort.SortFields.Add允许您指定将决定soring的订单字段。每个字段可以只是带有列标题的单元格。您可以为多个排序级别添加多个键。

To give an example, if you have data in cells A1:C10and you want to sort it in an ascending manner, taking information in column Aas the key for sorting, you can do this to set data in column Aas the key:

举个例子,如果你的单元格中有数据A1:C10,你想以升序方式对它进行排序,以列A中的信息作为排序的键,你可以这样做,将列A中的数据设置为键:

MainSheet.Sort.SortFields.Add Key:=Range("A1") '("A1:A10") will also work

And then you can specify the range that will be sorted based on that key as follows:

然后您可以指定将根据该键排序的范围,如下所示:

 MainSheet.Sort.SetRange Range("A1:C10")