gpt4 book ai didi

excel - 如何在 Powershell 中捕获 Excel 文件的宏错误?

转载 作者:行者123 更新时间:2023-12-04 20:53:02 24 4
gpt4 key购买 nike

我有一个预定的 PowerShell 脚本,它可以打开 Excel、打开一个文件并运行一个宏。
如果出现错误,我需要在 shell 中显示并中断脚本。 (我无法承受脚本在等待用户输入时挂起)

这是我当前的脚本(脚本前面定义了 $excelDataPath)

$Excel = New-Object -ComObject "Excel.Application"
$Excel.DisplayAlerts = $false
$Excel.AskToUpdateLinks = $false
$Excel.Visible = $true

$Workbook = $Excel.Workbooks.Open($excelDataPath)
$Excel.Run("Macro1")
$Workbook.Save()
$Workbook.Close($true)

谢谢

最佳答案

我认为从 PowerShell 的角度来看,这将捕获并显示已发生的异常:

try {
$Excel = New-Object -ComObject "Excel.Application"
$Excel.DisplayAlerts = $false
$Excel.AskToUpdateLinks = $false
$Excel.Visible = $true

$Workbook = $Excel.Workbooks.Open($excelDataPath)
$Excel.Run("Macro1")
$Workbook.Save()
$Workbook.Close($true)
$Excel.Close()
}
catch {
$exception = $_.Exception
while ($exception.InnerException) {
$exception = $exception.InnerException
}
# Throw a terminating error.
throw $exception
}
finally {
# IMPORTANT! Always release the comobjects used from memory when done
if ($Workbook) { [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Workbook) | Out-Null }
if ($Excel) { [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel) | Out-Null }
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}

但是,至于您没有向我们展示的 VBA 宏代码,您必须通过 VBA On Error Statement 查看它的功能是否有任何错误。 .尤其是 Err.RaiseThrow陈述。

关于excel - 如何在 Powershell 中捕获 Excel 文件的宏错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53740679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com