Skip to content

Instantly share code, notes, and snippets.

@urjeetpatel
Created October 23, 2018 16:27
Show Gist options
  • Save urjeetpatel/c9e2c95b31212dd29463e353570c4ed5 to your computer and use it in GitHub Desktop.
Save urjeetpatel/c9e2c95b31212dd29463e353570c4ed5 to your computer and use it in GitHub Desktop.
Delete Blank rows for all excel files in the current folder and subfolders
[threading.thread]::CurrentThread.CurrentCulture = 'en-US'
$excel = new-object -com excel.application;
$excel.visible = $true
$folders = Get-ChildItem -Directory
foreach ($folder in $folders)
{
cd $folder.FullName
$files = Get-ChildItem -Filter *.xlsx
foreach($file in $files){
$Workbook = $excel.Workbooks.Open($file.FullName)
$Worksheet = $Workbook.Worksheets.Item(1)
$used = $Worksheet.usedRange
try {
$done = $used.Columns("A:A").SpecialCells([Microsoft.Office.Interop.Excel.XlCellType]::xlCellTypeBlanks).EntireRow.Delete()
Write-host "Complete: $file"
}
Catch [System.Runtime.InteropServices.COMException]{
if ($_.Exception.Message -eq "No cells were found."){
Write-host "Skipping: $file : No blank rows"
}
elseif ($_.Exception.Message -eq "Unable to get the Delete property of the Range class"){
Write-host "Manual: $file"
While ($used.Columns("A:A").SpecialCells([Microsoft.Office.Interop.Excel.XlCellType]::xlCellTypeBlanks).Count -gt 0){
Write-host $used.Columns("A:A").SpecialCells([Microsoft.Office.Interop.Excel.XlCellType]::xlCellTypeBlanks).Count
Start-Sleep -s 10
}
}
else {
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Write-host $ErrorMessage ":" $file.FullName
}
}
Catch{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Write-host $ErrorMessage ":" $file.FullName
}
$Workbook.Save()
$Workbook.Close()
}
}
$excel.Quit()
Remove-Variable -Name used
Remove-Variable -Name Worksheet
Remove-Variable -Name Workbook
Remove-Variable -Name excel
[gc]::collect()
[gc]::WaitForPendingFinalizers()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment