I am trying to delete a named Worksheet from an .xlsm
file.
I followed the example posted here but it is not working for me. When I open the .xlsm
file to check whether the Worksheet has been deleted, it is still there.
Here is my code:
$file2 = 'c:\file.xlsm' # destination's fullpath
$xl = new-object -c excel.application
$xl.displayAlerts = $false # don't prompt the user
$wb2 = $xl.workbooks.open($file2) # open target
$sh2_wb2 = $wb2.sheets | where {$_.name -eq "myWorksheet"}
$sh2_wb2.delete() #Delete original sheet in template
$wb2.close($true) # close and save destination workbook
$xl.quit()
spps -n excel
What am I doing wrong?
Edit:
I changed my code to make the Excel Object visible when opening it. I then noticed that the delete
call is being sent, but it is asking the user to confirm whether the delete should happen: Data may exist in the sheet(s) selected for deletion. To permanently delete the data, press Delete.
I then attempted to add a few more displayAlerts = $false
in my code, but it is still giving me that prompt.
Here's my updated code, although it still does not work.
$file2 = 'c:\file.xlsm' # destination's fullpath
$xl = new-object -com excel.application -Property @{Visible = $true}
$xl.displayAlerts = $false # don't prompt the user
$wb2 = $xl.workbooks.open($file2) # open target
$wb2.displayAlerts = $false # don't prompt the user
$sh2_wb2 = $wb2.sheets | where {$_.name -eq "myWorksheet"}
$sh2_wb2.displayAlerts = $false # don't prompt the user
$sh2_wb2.delete() #Delete original sheet in template
$wb2.close($true) # close and save destination workbook
$xl.quit()
spps -n excel