Excel vba 排序标准——不同方向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17379738/
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
Excel vba Sorting Criteria –different orientations
提问by Leo308
I have a macro for sorting entries in four different sheets. Two of these I want to sort oriented left to right, while the other two must be sorted top to bottom. Right now the code looks roughly as follows (don't mind "MyRange” and “OtherRange” – they are variables decided outside this code):
我有一个宏,用于对四个不同工作表中的条目进行排序。其中两个我想从左到右排序,而另外两个必须从上到下排序。现在代码大致如下(不要介意“MyRange”和“OtherRange”——它们是在此代码之外决定的变量):
If MySheet.Name = "Shippers" _
Or MySheet.Name = "Consignees" _
Then
MySheet.sort.SortFields.Clear
MySheet.sort.SortFields.Add Key:=Range("MyRange”), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With MySheet.sort
.SetRange Range(“OtherRange”)
.Header = xlGuess
.MatchCase = False
.Orientation = xlLeftToRight '<---
.SortMethod = xlPinYin
.Apply
End With
Else
MySheet.sort.SortFields.Clear
MySheet.sort.SortFields.Add Key:=Range("MyRange”), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With MySheet.sort
.SetRange Range(“OtherRange”)
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom '<---
.SortMethod = xlPinYin
.Apply
End With
End If
The only real difference between the two blocks is the “.Orientation” – row. My question is: Is there any way to merge these two blocks and set “.Orientation” to either xlTopToBottom or xlLeftToRight depending on the sheet name?
两个块之间唯一真正的区别是“.Orientation” – 行。我的问题是:有没有办法合并这两个块并根据工作表名称将“.Orientation”设置为 xlTopToBottom 或 xlLeftToRight ?
采纳答案by KekuSemau
The xl~ constants are Long
values, you can just assign them to a variable before the block.
xl~ 常量是Long
值,您可以将它们分配给块之前的变量。
Dim OrntValue As Long
Select Case MySheet.Name
Case "Shippers", "Consignees"
OrntValue = xlLeftToRight
Case Else
OrntValue = xlTopToBottom
End Select
...
.Orientation = OrntValue
IIf
might be another option, but I'd prefer this one.
IIf
可能是另一种选择,但我更喜欢这个。