I am trying to delete entire row from excel based on search criteria, below is my code:
$file = "C:\Desktop\user.xlsx"
$excel = new-object -com Excel.Application -Property @{Visible = $false}
$workbook = $excel.Workbooks.Open($file)
$sheet = $workbook.Sheets.Item(1)
for($i = 1; $i -lt $($Workbook.Sheets.Count() + 1); $i++)
{
$Range = $Workbook.Sheets.Item($i).Range("A:Z")
$Target = $Range.Find($SearchString)
$First = $Target
Do
{
Write-Host "$($Target.AddressLocal())"
$stg= "$($Target.AddressLocal())"
$str= $stg.Substring(3)
[void]$sheet.Cells.Item($str,$str).EntireRow.Delete()
$Target = $Range.FindNext($Target)
}
While ($Target -ne $NULL -and $Target.AddressLocal() -ne First.AddressLocal())
}
$WorkBook.Save()
$WorkBook.Close($true)
$excel.quit()
i am able to search "Null" values and i could able to find the address of the string "null", but while
deleting i am facing below exception, please Help.
Note: when i pass address [void]$ws.Cells.Item(100,100).EntireRow.Delete()
,i could able to delete the row.
Exception from HRESULT: 0x800A03EC
At C:\desktop\Automation\1delet-excel-row-null.ps1:18 char:9
[void]$sheet.Cells.Item("$str","$str").EntireRow.Delete()
CategoryInfo: OperationStopped: (:) [], COMException
FullyQualifiedErrorId : System.Runtime.InteropServices.COMException