Good Morning Everyone! I have a tough problem. I have a workbook that has many worksheets (896). Each sheet is named “First Name(space)Last Name”. I would like to alphabetize the sheets A-Z using the last name. I have the below code which sorts them by first name. Thoughts on how I can use the second word to sort the sheets, rather than the first word? Any help is greatly appreciated!
# ===== Alphabetize Sheets ======
Add-Type -AssemblyName Microsoft.Office.Interop.Excel
$xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlWorkbookDefault
$Excel = New-Object -comobject Excel.Application
$Excel.Visible = $true
$workbook = $Excel.Workbooks.Open("$dir\Lochend Timesheet Reports for Period.xlsx")
$worksheetNames = New-Object System.Collections.ArrayList
foreach ($worksheet in $workbook.Worksheets) {
$worksheetNames.Add($worksheet.Name)
}
$worksheetNames.Sort()
for ($worksheetNamesIndex = 0; $worksheetNamesIndex -lt $worksheetNames.Count - 1; $worksheetNamesIndex++) {
$worksheetToMoveName = $worksheetNames[$worksheetNamesIndex]
$worksheetToMove = $workbook.Worksheets.Item($worksheetToMoveName)
$worksheet1After = $workbook.Worksheets.Item($worksheetNamesIndex + 1)
$worksheetToMove.Move($worksheet1After)
}
$Excel.ActiveWorkbook.SaveAs($dir + "\Lochend Timesheet Reports for Period $startRange to $endRange.xlsx", $xlFixedFormat)
$Excel.Workbooks.Close()
$Excel.Quit()