My Blog

Sorting Data

In continuation from here

There are times when you need to sort your data to a clearer representation. Depending upon your requirements, you might want to sort the data in ascending order or descending order. I have covered them both.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    '~~> Add a New Workbook
    xlWorkBook = xlApp.Workbooks.Add

    '~~> Display Excel
    xlApp.Visible = True

    '~~> Set the relebant sheet that we want to work with
    xlWorkSheet = xlWorkBook.Sheets("Sheet1")

    With xlWorkSheet
        '~~> Directly type the values that we want
        .Range("A1").Value = "Month"
        .Range("A2").Value = "January" : .Range("A3").Value = "February"
        .Range("A4").Value = "March" : .Range("A5").Value = "April"

        .Range("B1").Value = "Money Spent"
        .Range("B2").Value = "1000.00" : .Range("B3").Value = "1500.00"
        .Range("B4").Value = "1200.00" : .Range("B5").Value = "1100.00"

        '~~> To sort Ascending
        .Range("A1:B5").Sort(Key1:=.Range("B2"), Order1:=Excel.XlSortOrder.xlAscending, Header:=Excel.XlYesNoGuess.xlYes, _
            OrderCustom:=1, MatchCase:=False, Orientation:=Excel.XlSortOrientation.xlSortColumns, _

        '~~> To sort Descending change xlAscending to xlDescending above

        '~~> Autofitting text in columns
    End With
End Sub