如何避免删除只读,我需要正常的Excel而不是只读。我有以下代码:
$excelfile="C:\Users\Administrator\Pictures\unprotect_org - Copy\unprotect - Copy (2).xlsx"
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
$wb = $excel.Workbooks.Open($excelfile,$true,123)
$wb.SaveAs($excelfile,[Type]::Missing,$password)
$excel.Quit()
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Cannot save as that name. Document was opened as read-only.
At line:1 char:1
+ $wb.SaveAs($excelfile,[Type]::Missing,$password)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
Run Code Online (Sandbox Code Playgroud)
第二件事,为什么 microsoft execel 在任务管理器中打开,我怎样才能关闭这个 exe。

请帮我解决这个错误。
您需要更改两件事 - 以读写模式打开,并确保Quit()无论终止错误如何都会调用。
为了避免以只读模式打开工作簿,请更改传递给的第三个参数的值Open():
$wb = $excel.Workbooks.Open($excelfile,$true,$false)
# ^
# This is the ReadOnly parameter
Run Code Online (Sandbox Code Playgroud)
为了确保Quit()始终被调用,请使用try/finally语句:
$excelfile="C:\Users\Administrator\Pictures\unprotect_org - Copy\unprotect - Copy (2).xlsx"
$excel = New-Object -ComObject Excel.Application
try {
$excel.Visible = $false
$excel.DisplayAlerts = $false
$wb = $excel.Workbooks.Open($excelfile,$true,123)
$wb.SaveAs($excelfile,[Type]::Missing,$password)
}
finally {
$excel.Quit()
}
Run Code Online (Sandbox Code Playgroud)
如果 PowerShell 到达块内的第一个语句try,它保证finally块将在从块返回控制权之前执行 - 即使调用SaveAs()(或任何其他调用)抛出终止异常
| 归档时间: |
|
| 查看次数: |
532 次 |
| 最近记录: |