2014-02-10 74 views
0

我試圖從.xlsm文件中刪除一個命名的工作表。從.xlsm文件中刪除工作表

我跟着張貼here的例子,但它不適合我。當我打開.xlsm文件來檢查工作表是否已被刪除時,它仍然存在。

這裏是我的代碼:

$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 

我在做什麼錯?

編輯:

我改變了我的代碼,使打開時,Excel對象可見。然後我注意到delete呼叫正在發送,但它要求用戶確認是否刪除應該發生:Data may exist in the sheet(s) selected for deletion. To permanently delete the data, press Delete.

然後我嘗試添加一些displayAlerts = $false在我的代碼,但它仍然給我,提示。

這是我的更新代碼,但它仍然無法正常工作。

$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 
+0

你的代碼工作。你有執行權嗎? http://stackoverflow.com/questions/4037939/powershell-execution-of-scripts-is-disabled-on-this-system此外,你必須至少有一個可見的工作表,所以如果myWorksheet是唯一可見的,你會出錯。 –

+0

你讓我在正確的軌道上 - 請參閱我的編輯。 –

+0

從您的原始代碼中,如果myWorksheet上有數據,並且我將displayAlerts設置爲$ true,則表格不會被刪除。如果displayAlerts爲$ false,則表單將被刪除而不會出現問題。這是我正在測試的Excel 2010。 –

回答

0

試試這個,它幫助我:

$Excel = New-Object -ComObject Excel.Application 
$workbook = $Excel.workbooks.add() 
#working with sheets 
$workbook.worksheets.item("Sheet1").Delete()