简体   繁体   中英

Sorting operation using VBA?

How do I perform a sorting operation using VBA code ? Any defined macros to perform that ?

I have to sort my column B in ascending order which has values in it. And C column which has dates in it and in the fashion oldest to newest.

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. 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.

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. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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