Saturday, April 10, 2010

VBScript - Reverse the order of columns in an Excel Worksheet using Sort

VBScript - Reverse the order of columns in an Excel Worksheet using Sort

'Reverse the order of columns in an Excel Worksheet using Sort
'Based on my response in stackoverflow to
'"How to Reverse the Order of a Selected Range of Excel Columns using VBA"

xlNo = 2
xlDescending = 2
xlSortRows = 2
xlShiftDown = -4121

set xl = createobject("excel.application")
set wb = xl.Workbooks.add
set ws = wb.Worksheets(1)

xl.visible = true

'Add some data to excel
ws.Range("a1:d1").value = array("LAST NAME", "FIRST NAME", "AKA" , "AGE")
ws.Range("a2:d2").value = array("Parker" , "Peter" , "Spiderman" , 18 )
ws.Range("a3:d3").value = array("Parker" , "Benjamin" , "Uncle Ben" , 70 )
ws.Range("a4:d4").value = array("Myer" , "Ken" , "Dr. Scripto?", 3.14 )
ws.Range("a5:d5").value = array("Parker" , "May" , "Aunt May" , 70 )
ws.usedrange.columnwidth = 20

wscript.echo "Add Keys In First Row"

set r = ws.usedrange

r.rows(1).insert xlShiftDown
numCols = r.columns.count
redim keys(numCols)

for i = 0 to numCols
keys(i) = i
next

r.rows(0).value = keys

wscript.echo "Sort by first row"

set r = ws.usedrange
r.Sort r.rows(1), xlDescending, , , , , , xlNo, , , xlSortRows
wscript.echo "Remove Keys"

set r = ws.usedrange
r.rows(1).delete

[Via]