1

I need to sort an excel spreadsheet by sorting one column be ascending numbers so 1,2,3,4,5...

Does anyone know a quick and dirty way to sort a excel column in powershell?

5
  • Have you started working on a script? If so, please post what you have so far. Are you trying to sort only one column, or sort multiple columns based on the values in one column?
    – Rynant
    Apr 25, 2014 at 14:50
  • i just put in what i have so far. this gives me an error tho saying Exception calling "Sort" with "1" argument(s): "This operation requires the merged cells to be identically sized."
    – Peter3
    Apr 25, 2014 at 14:55
  • actually this code above works. my first header column was merged with a couple rows so it was preventing to sorting
    – Peter3
    Apr 25, 2014 at 14:57
  • Yeah, it was working for me as well. Glad you figured it out.
    – Rynant
    Apr 25, 2014 at 15:05
  • I'll move your code to your answer so that it fits with SE guidelines.
    – Rynant
    Apr 25, 2014 at 15:10

1 Answer 1

5
function Release-Ref ($ref) { 
    ([System.Runtime.InteropServices.Marshal]::ReleaseComObject( 
    [System.__ComObject]$ref) -gt 0) 
    [System.GC]::Collect() 
    [System.GC]::WaitForPendingFinalizers() 
} 
$objExcel = new-object -comobject excel.application 
$objExcel.Visible = $True 
$objWorkbook = $objExcel.Workbooks.Open("C:\test\flag for errors\1921BB.xls")
$objWorksheet = $objWorkbook.Worksheets.Item(1) 

$objRange = $objWorksheet.UsedRange 
$objRange2 = $objworksheet.Range("E1")  
[void] $objRange.Sort($objRange2) 
$objWorkbook.Save()
$a = Release-Ref($objWorksheet) 
$a = Release-Ref($objWorkbook) 
$a = Release-Ref($objExcel) 
3
  • Please come back after 48 hours and mark this as the accepted answer.
    – Adi Inbar
    Apr 26, 2014 at 3:59
  • This script works but I'm having trouble with the Excel file being fully "released". I.e., when I manually open the Excel file after using the script, I get a notification stating that the file is Read Only because it's still in use. When I open Task Manager, the EXCEL process is still running even though the file is closed.
    – user5954196
    Feb 11, 2019 at 13:41
  • Problem was fixed by adding $objWorkbook.Close() just after the $objWorkbook.Save() statement.
    – user5954196
    Feb 11, 2019 at 13:44

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.