首页 > 解决方案 > 如何使用 Powershell 在打开的 Excel 工作簿上运行 vba 程序

问题描述

我正在构建一个 powershell 脚本来搜索指定打开的 excel 工作簿并在其上运行 vba。

当有一个带有多个工作簿的 excel 应用程序时,它运行良好。

但是,当有多个 excel 应用程序时,它不起作用,因为代码仅在一个 excel 应用程序上搜索工作簿。如何在所有打开的 Excel 应用程序上搜索工作簿?

这是我正在使用的代码

Try{
    # Check if any excel application is running
    $ExistingExcel = ((get-process excel | select MainWindowTitle, ID, StartTime | 
    Sort StartTime)).mainwindowtitle

    # Get existing excel application
    $excel = [Runtime.Interopservices.Marshal]::GetActiveObject('Excel.Application')

    # Get a list of workbook name in the excel application
    $ExcelList = $excel.workbooks | Foreach-object {$_.name}

    # Check if the list of workbooks contain the target workbook
    $targetWb = if ($ExcelList -contains "MyTargetWorkbook.xlsm") 
    {
         # Activate the target workbook and run the vba
         $excel.Workbooks.Item("MyTargetWorkbook.xlsm")
         $targetwb.Activate()
         $excel.run('MyVbaProgram')

    } else {
        # Do error handling
    }

}Catch{
    # Do error handling
}    

标签: vbaexcelpowershellworksheet

解决方案


推荐阅读