Created
October 23, 2018 16:27
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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