【发布时间】:2019-01-09 09:30:35
【问题描述】:
我正在尝试创建允许我打开 excel 文件、运行宏、然后保存文件并关闭它的 PowerShell 脚本。我的代码如下:
$excel = New-Object -ComObject Excel.Application
$MacroName1 = "Extraction_Tool.xlsm"
$currentExecutingPath = $fullPathIncFileName.Replace($currentScriptName, "") + $MacroName
$ExcelFiles = Get-ChildItem -Path $currentExecutingPath
$Workbook = $excel.Workbooks.Open($currentExecutingPath)
$excel.Application.DisplayAlerts = $False
$excel.Run("refreshall")
$excel.ActiveWorkbook.Save()
$workbook.Close()
$excel.Quit()
当我运行这个脚本时,我收到错误:
您不能在空值表达式上调用方法。 在 W:\GDA_files\SME_iQA\iQA_NEW\PrepareMacro.ps1:10 char:1 + $excel.ActiveWorkbook.Save() + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNullVBA 宏 (refreshall) 大约需要一分钟。您是否认为该脚本无法保存文件,因为它在宏运行时尝试执行此操作?
【问题讨论】:
-
错误信息明确指出
$excel.ActiveWorkbook为空。请改用$workbook.Save()。 -
您好 Ansgar,感谢您的回复。带代码:
$workbook.Save() $workbook.Close()我收到:Method invocation failed because [System.__ComObject] doesn't contain a method named 'Save'. At W:\GDA_files\SME_iQA\iQA_NEW\PrepareMacro.ps1:10 char:1 + $workbook.Save() + ~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (Save:String) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound
标签: excel vba powershell