Friday, April 9, 2010

VBScript-Sort excel Worksheets

VBScript - How Can I Sort Worksheets in a Excel Workbook?

On Error Resume Next

Dim arrNames()
intSize = 0

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True

Set objWorkbook = objExcel.Workbooks.Open("C:\Scripts\Inventory.xls")

For Each objWorksheet in objWorkbook.Sheets
ReDim Preserve arrNames(intSize)
arrNames(intSize) = objWorksheet.Name
intSize = intSize + 1
Next

For i = (UBound(arrNames) - 1) to 0 Step -1
For j= 0 to i
If UCase(arrNames(j)) > UCase(arrNames(j+1)) Then
strHolder = arrNames(j+1)
arrNames(j+1) = arrNames(j)
arrNames(j) = strHolder
End If
Next
Next

For i = UBound(arrNames) to 1 Step -1
Set objSheet1 = objWorkbook.Sheets(arrNames(i))
Set objSheet2 = objWorkbook.Sheets(arrNames(i-1))
objSheet2.Move objSheet1
Next

[Via]