简体   繁体   English

使用VBA进行排序操作?

[英]Sorting operation using VBA?

How do I perform a sorting operation using VBA code ? 如何使用VBA代码执行排序操作? Any defined macros to perform that ? 有定义的宏可以执行该操作吗?

I have to sort my column B in ascending order which has values in it. 我必须按升序对B列进行排序,其中具有值。 And C column which has dates in it and in the fashion oldest to newest. 和C列,其中以最早和最新的方式显示日期。

I highly reccomend you play around with the macro recorder. 我强烈建议您使用宏录制器。 If you do not see a developer tab in your Excel, go to excel options and it should be in the Popular tab. 如果您在Excel中看不到“开发人员”选项卡,请转到excel选项,它应位于“流行”选项卡中。 Click to turn it on. 单击以将其打开。

Press Record Macro, then do the thing you want to do (like highlight a column and press Sort on the ribbon and sort by ascending) then Stop Recording. 按“记录宏”,然后做您想做的事情(例如突出显示一列,然后按功能区上的“排序”并按升序排序),然后“停止记录”。 Go into VBA (Alt+F11) and see the resulting code to learn the syntax on how to write the same function. 进入VBA(Alt + F11)并查看生成的代码,以学习有关如何编写相同函数的语法。

For example, sort dates will result in something like this: 例如,排序日期将导致如下所示:

Sub Macro1()
    Columns("F:F").Select
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("F1:F5"), _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet1").Sort
        .SetRange Range("F1:F5")
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

Since you will already select the column you want to sort when you run your macro, you can clean the code up to something like this: 由于您已经在运行宏时选择了要排序的列,因此可以将代码清理为如下所示:

Sub SortAscending()
    With ActiveWorkbook.Worksheets("Sheet1").Sort
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

Sorting dates can be done with the same codes since it's ascending order: 由于排序日期是升序,因此可以使用相同的代码进行排序:

The trick is to remember that you don't need to select the range in the code that you are already selecting. 诀窍是要记住,您不必在已经选择的代码中选择范围。 Good luck and have fun with the recorder, it really does help in cases like this. 祝您好运,并喜欢录音机,它在这种情况下确实有帮助。

Also, there are numerous books on Excel VBA and I reccomend you picking one up at the book store or digitally. 另外,在Excel VBA上有很多书籍,我建议您在书店或以数字方式购书。 Most books out there will walk you through the basic of understanding VBA basics, main keywords, using the recorder, then eventually far along enough so you can write your own code (recorder code is hardly optimized or perfect, but is great for learning the wording (syntax) for doing some worksheet functions). 那里的大多数书籍都会带您逐步了解VBA基础知识,主要关键字,使用记录器,然后逐步学习,以便您可以编写自己的代码(记录器代码几乎没有优化或完善,但是对于学习措辞非常有用(语法)以执行某些工作表功能)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM