Saturday, April 3, 2010

How to sort rows in Excel using VBScript

How to sort rows in Excel using VBScript

Const xlAscending = 1
Const xlDescending = 2
Const xlYes = 1

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Add
Set objWorksheet = objWorkbook.Worksheets(1)

objExcel.Cells(1, 1).Value = "Number"
objExcel.Cells(2, 1).Value = "9"
objExcel.Cells(3, 1).Value = "2"
objExcel.Cells(4, 1).Value = "60"
objExcel.Cells(5, 1).Value = "0"
objExcel.Cells(6, 1).Value = "8"
objExcel.Cells(7, 1).Value = "2"
objExcel.Cells(1, 2).Value = "Letter"
objExcel.Cells(2, 2).Value = "B"
objExcel.Cells(3, 2).Value = "C"
objExcel.Cells(4, 2).Value = "P"
objExcel.Cells(5, 2).Value = "K"
objExcel.Cells(6, 2).Value = "J"
objExcel.Cells(7, 2).Value = "O"

Set objRange = objWorksheet.UsedRange
Set objRange2 = objExcel.Range("A1")
objRange.Sort objRange2, xlAscending, , , , , , xlYes

Change A1 to B1 in the second last line and it will sort the column "Letter"

[Via]