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? Commented 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." Commented 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 Commented Apr 25, 2014 at 14:57
  • Yeah, it was working for me as well. Glad you figured it out. Commented Apr 25, 2014 at 15:05
  • I'll move your code to your answer so that it fits with SE guidelines. Commented 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) 
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Problem was fixed by adding $objWorkbook.Close() just after the $objWorkbook.Save() statement.

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.