VBA Excel 按特定列对范围进行排序

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

VBA Excel sort range by specific column

excelvbasorting

提问by Cheese

I have a table that can contain any number of rows:

我有一个可以包含任意行数的表:

enter image description here

在此处输入图片说明

As I said it can contain 1 or ∞ rows.

正如我所说,它可以包含 1 或 ∞ 行。

I want to sort range A3:D∞by the Date cell that is in column B.
How can I do it?

我想A3:D∞按 B 列中的日期单元格对范围进行排序。
我该怎么做?

The problem is that I don't know how to select from A3to the last row.

问题是我不知道如何从A3最后一行选择。

I think that looping to the last row is not a correct method.

我认为循环到最后一行不是正确的方法。

I have got this so far it sorts looks like correct, but the range is hard-coded.
How do I get rid of the hard-coding of the range?

到目前为止,我已经得到了它,它看起来是正确的,但范围是硬编码的。
如何摆脱范围的硬编码?

Range("A3:D8").Sort key1:=Range("B3:B8"), _
order1:=xlAscending, Header:=xlNo

回答by Dmitry Pavliv

Try this code:

试试这个代码:

Dim lastrow As Long
lastrow = Cells(Rows.Count, 2).End(xlUp).Row
Range("A3:D" & lastrow).Sort key1:=Range("B3:B" & lastrow), _
   order1:=xlAscending, Header:=xlNo

回答by L42

Or this:

或这个:

Range("A2", Range("D" & Rows.Count).End(xlUp).Address).Sort Key1:=[b3], _
    Order1:=xlAscending, Header:=xlYes

回答by Simi

If the starting cell of the range and of the key is static, the solution can be very simple:

如果范围和键的起始单元格是静态的,则解决方案可能非常简单:

Range("A3").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Sort key1:=Range("B3", Range("B3").End(xlDown)), _
order1:=xlAscending, Header:=xlNo