# Trying to sort a excel column

**URL:** <https://forums.powershell.org/t/trying-to-sort-a-excel-column/18953>\
**Category:** PowerShell Help\
**Created:** [March 30, 2022, 2:31pm UTC](https://forums.powershell.org/t/trying-to-sort-a-excel-column/18953 "2022-03-30T14:31:02Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![TomP](https://avatars.discourse-cdn.com/v4/letter/t/3da27b/32.png) [@TomP](https://forums.powershell.org/u/TomP)\
**Post date:** [March 30, 2022, 2:31pm UTC](https://forums.powershell.org/t/trying-to-sort-a-excel-column/18953/1 "2022-03-30T14:31:02Z")

</div>

My PS script is taking a .csv file and creating a excel .xlsx spreadsheet. I want to sort a particular column so the number come out in descending order.. I tried several changes to the sort code and still getting the error.  
Unable to get the Sort property of the Range class  
At H:\GoogleAnalytics\PowershellScripts\Sample1.ps1:79 char:1

- [void] $objRange2.Sort($objRange)

# This will open the .csv file from above and write it out as an Excel Spreadsheet

Write-Host “Begin converting the .csv report file to an Excel .XLSX Spreadsheet”  
$csv = “H:/GoogleAnalytics/reports/”+$reportname+“_webstats_”+$datetime+“.csv” #Location of the source file  
$xlsx = “H:/GoogleAnalytics/reports/”+$reportname+“_webstats_”+$datetime+“.xlsx” #Desired location of output  
$delimiter = “,” #Specify the delimiter used in the file

# Create a new Excel workbook with one empty sheet

$excel = New-Object -ComObject excel.application

$workbook = $excel.Workbooks.Add(1)  
$worksheet = $workbook.worksheets.Item(1)  
$objRange = $worksheet.UsedRange  
$objRange2 = $worksheet.Range(“C3”)  
[void] $objRange2.Sort($objRange)  
$worksheet.Name = $reportname  
$worksheet.Cells.Item(1,1) = $TitleOfReport # get title of report from above variable  
$result = $len - 8  
$urltitle = $reportname.SubString(0,$result)  
$urltitle = $urltitle+’ urls’  
$worksheet.Cells.Item(1,2) = $urltitle.ToUpper()  
$worksheet.Cells.Item(1,1).Font.Bold=$True # make the Report Title in cell A1 Bold  
$worksheet.Cells.Item(1,2).Font.Bold=$True # make the Dept URL in cell B1 Bold  
$worksheet.Cells.Item(2,1).Font.Bold=$True # make the Page Title in cell A2 Bold  
$worksheet.Cells.Item(2,2).Font.Bold=$True # make the Page in cell B2 Bold  
$worksheet.Cells.Item(2,3).Font.Bold=$True # make the Page Views in cell C2 Bold  
$worksheet.Cells.Item(2,4).Font.Bold=$True # make the Avg Time on Pages in cell D2 Bold  
$worksheet.Cells.Item(2,5).Font.Bold=$True # make the Users in cell E2 Bold

# Build the QueryTables.Add command and reformat the data

$TxtConnector = (“TEXT;” + $csv)  
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range(“A2”))  
$query = $worksheet.QueryTables.item($Connector.name)  
$query.TextFileOtherDelimiter = $delimiter  
$query.TextFileParseType = 1  
$query.TextFileColumnDataTypes = ,1 \* $worksheet.Cells.Columns.Count  
$query.AdjustColumnWidth = 1

# Execute & delete the import query

$query.Refresh()  
$query.Delete()

# Save & close the Workbook as XLSX.

$Workbook.SaveAs($xlsx,51)  
Write-Host “Excel Spreadsheet Report found at: H:/GoogleAnalytics/reports/”$reportname’_webstats_’$datetime".XLSX"  
$excel.Quit()  
#get-process _excel_ | stop-process -force  
Write-Host “Deleting the .CSV Report file now that the Excel Spreadsheet has been created”  
Remove-Item -path .\GoogleAnalytics\reports$reportname’_webstats_’$datetime.csv  
Write-Host “Process Completed”

---

<div class="post-metadata">

**Author:** ![matt-bloomfield](https://avatars.discourse-cdn.com/v4/letter/m/dec6dc/32.png) [@matt-bloomfield](https://forums.powershell.org/u/matt-bloomfield)\
**Post date:** [March 30, 2022, 2:51pm UTC](https://forums.powershell.org/t/trying-to-sort-a-excel-column/18953/2 "2022-03-30T14:51:09Z")

</div>

Please can you edit your post and use the **\</\>** button to format your code. This will make it much more readable and enable us to copy and paste for testing.

> [@Welcome to the new PowerShell Forums](https://forums.powershell.org/t/welcome-to-the-new-powershell-forums/7/6):
>
> How to format code in [PowerShell.org](http://PowerShell.org) forums. [Codeformatting\_1]

---

<div class="post-metadata">

**Author:** ![TomP](https://avatars.discourse-cdn.com/v4/letter/t/3da27b/32.png) [@TomP](https://forums.powershell.org/u/TomP)\
**Post date:** [March 31, 2022, 3:42pm UTC](https://forums.powershell.org/t/trying-to-sort-a-excel-column/18953/3 "2022-03-31T15:42:17Z")

</div>

```auto
This will open the .csv file from above and write it out as an Excel Spreadsheet
Write-Host “Begin converting the .csv report file to an Excel .XLSX Spreadsheet”
$csv = “H:/GoogleAnalytics/reports/”+$reportname+“webstats”+$datetime+".csv" #Location of the source file
$xlsx = “H:/GoogleAnalytics/reports/”+$reportname+“webstats”+$datetime+".xlsx" #Desired location of output
$delimiter = “,” #Specify the delimiter used in the file

Create a new Excel workbook with one empty sheet
$excel = New-Object -ComObject excel.application

$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)
$objRange = $worksheet.UsedRange
$objRange2 = $worksheet.Range(“C3”)
[void] $objRange2.Sort($objRange)
$worksheet.Name = $reportname
$worksheet.Cells.Item(1,1) = $TitleOfReport # get title of report from above variable
$result = $len - 8
$urltitle = $reportname.SubString(0,$result)
$urltitle = $urltitle+’ urls’
$worksheet.Cells.Item(1,2) = $urltitle.ToUpper()
$worksheet.Cells.Item(1,1).Font.Bold=$True # make the Report Title in cell A1 Bold
$worksheet.Cells.Item(1,2).Font.Bold=$True # make the Dept URL in cell B1 Bold
$worksheet.Cells.Item(2,1).Font.Bold=$True # make the Page Title in cell A2 Bold
$worksheet.Cells.Item(2,2).Font.Bold=$True # make the Page in cell B2 Bold
$worksheet.Cells.Item(2,3).Font.Bold=$True # make the Page Views in cell C2 Bold
$worksheet.Cells.Item(2,4).Font.Bold=$True # make the Avg Time on Pages in cell D2 Bold
$worksheet.Cells.Item(2,5).Font.Bold=$True # make the Users in cell E2 Bold

Build the QueryTables.Add command and reformat the data
$TxtConnector = (“TEXT;” + $csv)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range(“A2”))
$query = $worksheet.QueryTables.item($Connector.name)
$query.TextFileOtherDelimiter = $delimiter
$query.TextFileParseType = 1
$query.TextFileColumnDataTypes = ,1 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1

Execute & delete the import query
$query.Refresh()
$query.Delete()

Save & close the Workbook as XLSX.
$Workbook.SaveAs($xlsx,51)
Write-Host “Excel Spreadsheet Report found at: H:/GoogleAnalytics/reports/”$reportname’webstats’$datetime".XLSX"
$excel.Quit()
#get-process excel | stop-process -force
Write-Host “Deleting the .CSV Report file now that the Excel Spreadsheet has been created”
Remove-Item -path .\GoogleAnalytics\reports$reportname’webstats’$datetime.csv
Write-Host “Process Completed”

```

---

<div class="post-metadata">

**Author:** ![matt-bloomfield](https://avatars.discourse-cdn.com/v4/letter/m/dec6dc/32.png) [@matt-bloomfield](https://forums.powershell.org/u/matt-bloomfield)\
**Post date:** [March 31, 2022, 9:42pm UTC](https://forums.powershell.org/t/trying-to-sort-a-excel-column/18953/4 "2022-03-31T21:42:05Z")

</div>

That’s not much better, now you’ve got code mixed with your comments.

Everyone here gives up their free time to help answer queries. Please help us by taking a few minutes to format your posts properly.

What, exactly, are you trying to sort? In your code you’re calling the `Sort` method on `$ObjRange2` but you’ve defined that range as a single cell, C3.

If you want to sort the items in the range you’ve defined using the `UsedRange` property, then use:

```auto
$objRange.Sort($objRange)

```

Otherwise, define your range first:

```auto
$myRange = $worksheet.Range("D2:D7")
$myRange.Sort($myRange)

```

---

<div class="post-metadata">

**Author:** ![TomP](https://avatars.discourse-cdn.com/v4/letter/t/3da27b/32.png) [@TomP](https://forums.powershell.org/u/TomP)\
**Post date:** [April 4, 2022, 1:01pm UTC](https://forums.powershell.org/t/trying-to-sort-a-excel-column/18953/5 "2022-04-04T13:01:09Z")

</div>

Thanks for your help. After replacing your 2 statements the column in the original order.  
I want the column to be in descending order.

```auto
Write-Host "Begin converting the .csv report file to an Excel .XLSX Spreadsheet"
$reportname = "baseball"
$csv = "H:/GoogleAnalytics/baseball.csv"    
$xlsx = "H:/GoogleAnalytics/reports/baseball.xlsx"  
$delimiter = "," #Specify the delimiter used in the file
$date = Get-Date -Format yyyy-MM-dd 
$time = get-date -Format HHmmss
$datetime = $date + "-" + $time
$excel = New-Object -ComObject excel.application
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)
$worksheet.Name = $reportname
$myRange = $worksheet.Range("B1:B7")
$myRange.Sort($myRange)
$TxtConnector = ("TEXT;" + $csv)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)
$query.TextFileOtherDelimiter = $delimiter
$query.TextFileParseType = 1
$query.TextFileColumnDataTypes = ,1 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1
$query.Refresh()
$query.Delete()
$Workbook.SaveAs($xlsx,51)
$excel.Quit()
```

---

<div class="post-metadata">

**Author:** ![matt-bloomfield](https://avatars.discourse-cdn.com/v4/letter/m/dec6dc/32.png) [@matt-bloomfield](https://forums.powershell.org/u/matt-bloomfield)\
**Post date:** [April 4, 2022, 1:47pm UTC](https://forums.powershell.org/t/trying-to-sort-a-excel-column/18953/6 "2022-04-04T13:47:39Z")

</div>

Sorry, missed that. You just need to specify a value for the sort order:

> **[XlSortOrder enumeration (Excel)](https://docs.microsoft.com/en-us/office/vba/api/excel.xlsortorder)**
>
> Office VBA reference topic

```auto
$myRange.Sort($myRange,2)

```

---

<div class="post-metadata">

**Author:** ![TomP](https://avatars.discourse-cdn.com/v4/letter/t/3da27b/32.png) [@TomP](https://forums.powershell.org/u/TomP)\
**Post date:** [April 4, 2022, 2:19pm UTC](https://forums.powershell.org/t/trying-to-sort-a-excel-column/18953/7 "2022-04-04T14:19:57Z")

</div>

Thanks Matt. I added the XISortOrder number 2 for descending… The column still comes out in the order of the .csv file. I created this simple 2 column .csv file. Column A has a team name, column B has a 3 digit number. There are only 7 rows… Do you have any idea why the sort is not working?

---

<div class="post-metadata">

**Author:** ![matt-bloomfield](https://avatars.discourse-cdn.com/v4/letter/m/dec6dc/32.png) [@matt-bloomfield](https://forums.powershell.org/u/matt-bloomfield)\
**Post date:** [April 4, 2022, 2:34pm UTC](https://forums.powershell.org/t/trying-to-sort-a-excel-column/18953/8 "2022-04-04T14:34:39Z")

</div>

Are you adding the data to the sheet after you apply the sort? It appears that way from your script.

You should populate the data, then define the range where the data occurs, then sort.

Edit:  
Incidently, the code I gave only sorts 1 column. If the value in column B is associated with the value in column A, you need to specify the range to be sorted, and the range you want to sort on:

```auto
$rangeToSort = $worksheet.usedRange
$rangeToSortBy = $workSheet.Range("B1:B7")
$rangeToSort.Sort($rangeToSortBy,2)

```

---

<div class="post-metadata">

**Author:** ![dotnVo](https://avatars.discourse-cdn.com/v4/letter/d/4af34b/32.png) [@dotnVo](https://forums.powershell.org/u/dotnVo)\
**Post date:** [May 16, 2024, 8:18pm UTC](https://forums.powershell.org/t/trying-to-sort-a-excel-column/18953/9 "2024-05-16T20:18:06Z")

</div>

Closed on May 16, 2024, 8:18pm UTC


