vba 用于排序的 Excel 常量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11766118/
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-11 17:08:33  来源:igfitidea点击:

Excel Constants for Sorting

excelvbaexcel-vba

提问by C0ppert0p

I'm using the sort procedure in Excel VBA and want to have a variable set that changes the order to ascending or descending, depending on a condition. I tried this but am getting a "type mismatch" error.

我在 Excel VBA 中使用排序过程,并希望有一个变量集,根据条件将顺序更改为升序或降序。我试过了,但出现“类型不匹配”错误。

If SBF = 0 Then
    S = "xlAscending"
Else: S = "xlDescending"
End If  
ActiveWorkbook.Worksheets(SN(x)).sort.SortFields.Add Key:=Range( _
        "B3:B" & last_cell), SortOn:=xlSortOnValues, Order:=S, DataOption:= _
        xlSortNormal

回答by C0ppert0p

This works:

这有效:

Public Enumeration, XlSortOrder, instance

Dim instance As XlSortOrder
If SBF = 0 Then
    instance = xlAscending
Else: instance = xlDescending
End If
ActiveWorkbook.Worksheets(SN(x)).sort.SortFields.Add Key:=Range( _
    "B3:B" & last_cell), SortOn:=xlSortOnValues, Order:=instance, DataOption:= _
    xlSortNormal

回答by Siddharth Rout

xlAscendingand xlDescendingare Excel Constants. To see what values they have simply print it in Immediate window. See the snapshot below.

xlAscendingxlDescending是 Excel 常量。要查看他们有什么值,只需在立即窗口中打印即可。请参阅下面的快照。

enter image description here

在此处输入图片说明

So you can actually write your code as

所以你实际上可以把你的代码写成

If SBF = 0 Then S = 1 Else S = 2

ActiveWorkbook.Worksheets(SN(x)).Sort.SortFields.Add _
Key:=Range("B3:B" & last_cell), _
SortOn:=xlSortOnValues, _
Order:=S, _
DataOption:=xlSortNormal

Similarly the values of xlSortOnValuesand xlSortNormalis 0. If you want you can also write the above code as

类似地,xlSortOnValues和 的xlSortNormal值为0。如果你愿意,你也可以把上面的代码写成

If SBF = 0 Then S = 1 Else S = 2

ActiveWorkbook.Worksheets(SN(x)).Sort.SortFields.Add _
Key:=Range("B3:B" & last_cell), _
SortOn:=0, _
Order:=S, _
DataOption:=0

EDIT

编辑

I am assuming that Shas been declared as an Integer or a Long and not as a String.

我假设S已声明为 Integer 或 Long 而不是 String。