I want to delete many Excel files in folder at once.
So I write below code, but when it runs, terminal logged out Delete Method of Range class failed
error popping up.
and more confusing thing, in some worksheet's delete process runs successfully.
I think, it causes from can not do release sheet object of powershell well.
can anybody help me? regards.
# Launch Excel
$excel = New-Object -ComObject Excel.Application -Property @{Visible = $false}
$baseDir = Convert-Path $(Split-Path $MyInvocation.InvocationName -Parent)
$files = Get-ChildItem -Recurse | ? { $_.Extension -eq ".xlsx" }
# "${baseDir}\{$_.name}"
# Open Book
$files|
%{
Write-Host $_.Name
$excel.Workbooks.Open("${baseDir}\" + $_.name) | %{
$_.Worksheets | %{
# Delete Column
# $_.Activate
Write-Host $_.Name
#$_.Columns.Item("J").Delete()
#$_.Columns("J:J").EntireColumn.Delete()
#$_.Columns.item(3).Insert()
#$_.Range("J:J").Delete()
$_.Columns("J").Delete()
}
$_.Save()
}
}
# Excel
$excel.Quit()
\[System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($excel) | Out-Null