vba 如何从左到右对列进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23900028/
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
How to sort columns left to right?
提问by Robin Trietsch
I'm trying to sort the columns, based on the values shown in a certain row.
我正在尝试根据特定行中显示的值对列进行排序。
The data consists of two tables, separated by an empty line.
数据由两个表组成,由空行分隔。
A B C D E
1 12QA03 12QA01 12QA02
2 Step 1 32 23 82
3 Step 2 43 92 1
4 Step 3 12 12 84
5 Step 4 65 89 51
6
7 24QA93 24QA91 24QA95 24QA98
8 Step 1 94 77 83 28
9 Step 2 92 30 5 19
10 Step 3 19 82 16 49
11 Step 4 11 41 7 17
The goal is to get this:
目标是得到这个:
A B C D E
1 12QA01 12QA02 12QA03
2 Step 1 23 82 32
3 Step 2 92 1 43
4 Step 3 12 84 12
5 Step 4 89 51 65
6
7 24QA91 24QA93 24QA95 24QA98
8 Step 1 77 94 83 28
9 Step 2 30 92 5 19
10 Step 3 82 19 16 49
11 Step 4 41 11 7 17
I have written a macro that works properly for the top table, but gives an error for the second:
我已经编写了一个适用于顶级表的宏,但在第二个表中出现错误:
Sub SortData()
'Sort top table
With Range("B1:D5")
.Rows.Sort Key1:=.Rows.Range("B1"), Order1:=xlAscending, _
Orientation:=xlLeftToRight
End With
'Sort top table
With Range("B7:E11")
.Rows.Sort Key1:=.Rows.Range("B7"), Order1:=xlAscending, _
Orientation:=xlLeftToRight
End With
End Sub
What is going wrong? Or might there be a better method? Thanks in advance for your help!
出了什么问题?或者可能有更好的方法?在此先感谢您的帮助!
回答by pnuts
A little simpler perhaps:
也许更简单一点:
Sub SortLTable()
Range("B7:E11").Sort Key1:=Range("B7:E7"), Order1:=xlAscending, Orientation:=xlLeftToRight
End Sub
回答by Robin Trietsch
The following code works.
以下代码有效。
Sub SortLTable()
Range("B1:D5").Sort Key1:=Range("B1:D1"), Order1:=xlAscending, Orientation:=xlLeftToRight
Range("B7:E11").Sort Key1:=Range("B7:E7"), Order1:=xlAscending, Orientation:=xlLeftToRight
End Sub
回答by Andy G
Put something in A1 and A7 temporarily, such as "A", so that you have complete tables (with filled header columns). You can remove these values after sorting.
在 A1 和 A7 中临时放置一些东西,例如“A”,以便您拥有完整的表格(带有填充的标题列)。您可以在排序后删除这些值。
Your use of With
and Rows
is confusing the issue though:
但是,您对With
and 的使用Rows
使问题变得混乱:
Sub SortData()
'Sort top table
Range("A1,A7").Value = "A"
Range("B1:D5").Sort Key1:=Range("B1"), Order1:=xlAscending, _
Orientation:=xlLeftToRight
'Sort top table
Range("B7:E11").Sort Key1:=Range("B7"), Order1:=xlAscending, _
Orientation:=xlLeftToRight
Range("A1,A7").Value = ""
End Sub