3

So I'm importing a CSV, formatting the date column and saving as an XLS file.

I'd like to be able to sort the date column. I have the following code and am stumped on how to sort the column. The date column is column 4 and has "date" as the header in the 1st row

$xl = new-object -comobject excel.application
$xl.visible = $false
$Workbook = $xl.workbooks.open(“$destination")
$xl.columns.autofit() >$null
$xl.Columns.Item('D').NumberFormat = "MM/dd/yyy"
$Workbook.SaveAs($final,1)
$Workbook.Saved = $True
$xl.Quit()

I've recorded the following macro yet cannot decipher how to change it to powershell. Any help is appreciated

Sub Macro1()
'
' Macro1 Macro
'

'
   Columns("D:D").Select
     ActiveWorkbook.Worksheets("newreport").Sort.SortFields.Clear
     ActiveWorkbook.Worksheets("newreport").Sort.SortFields.Add Key:=Range("D1"), _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("newreport").Sort
        .SetRange Range("A1:F251")
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub
3
  • 5
    Sort it with Sort-Object when you import the CSV? e.g. Import-Csv x.csv | Sort-Object -Property { [datetime]$_.Date } | ... Commented Jul 29, 2017 at 6:38
  • Brilliant!! Thank you :) Commented Jul 29, 2017 at 7:04
  • There is a small bug in your recording: it should read .Header = xlYes if you want to mark the first row as header. Commented Dec 15, 2020 at 8:31

1 Answer 1

3

It is very easy!

$empty_Var = [System.Type]::Missing
$sort_col = $objWorkSheet.Range("A1:A255")
$objWorkSheet.UsedRange.Sort($sort_col,1,$empty_Var,$empty_Var,$empty_Var,$empty_Var,$empty_Var,1)

For the Sort method arguments meaning, you can check office vba manual:https://learn.microsoft.com/en-us/office/vba/api/excel.range.sort

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.