Problem : Sorting an Excel worksheet with header row in powershell
I’m trying to learn powershell from a vbscript background and for the life of me I can’t figure out how to properly sort a worksheet in powershell.
I want to sort descending on column H, but I have a header row, so I’d like to start on cell H2.
How would I do something like this? And how would I sort on 2 separate columns? I can’t seem to find any references specifically for powershell on the web.
1: 2: 3: 4: 5: 6: |
$excel = New-Object -ComObject excel.application $excel.visible=$true $wb = $excel.Workbooks.Open("C:\scripts\worksheet.xls") $ws = $wb.Worksheets.item(1) $range=$ws.usedrange $range.Sort($ws.range("h2"),2) |
Solution : Sorting an Excel worksheet with header row in powershell
Though the official VBA syntax is
> $range.Sort
outputs the following syntax:
OverloadDefinitions : {Variant Sort (Variant, XlSortOrder, Variant, Variant, XlSor
tOrder, Variant, XlSortOrder, XlYesNoGuess, Variant, Variant
, XlSortOrientation, XlSortMethod, XlSortDataOption, XlSortD
ataOption, XlSortDataOption)}
TypeName
Value : Variant Sort (Variant, XlSortOrder, Variant, Variant, XlSort
Order, Variant, XlSortOrder, XlYesNoGuess, Variant, Variant,
XlSortOrientation, XlSortMethod, XlSortDataOption, XlSortDa
taOption, XlSortDataOption)
Name : Sort
IsInstance : True
The two variants after the first XlSortOrder are puzzling. I tried and had success by ignoring the first variant of those:
> $range.Sort($ws.Range(“J:J
But don’t ask me more – has been my first time I tried to access Excel thru PS. It is not the way PS is supposed to be used – Chris-Dent’s approach is in fact PS-stylish.