让 PowerShell 等待 Excel 完成刷新数据透视表

Ram*_*nes 2 excel powershell vba

所以我开发了一个Powershell脚本来刷新大约40个大的excel文件并保存它们,在这个脚本中我运行一个excel宏来传递excel(ODBC)连接参数,然后在刷新完成后从excel文件中删除它们。我唯一的问题是(对于这 40 个文件中的 5 个文件)启动 RefreshAll 命令时,Powershell 不会等待 Excel 完成刷新,而是传递到下一个命令,该命令是使连接无效的宏,从而导致错误宏中的“1004”(文件仍在刷新时无法访问 Excel 连接。)

经过一番研究,我知道在Powershell v2中,有后台作业的概念,但就我而言,这不是一个旁白进程,它属于Excel进程,所以我的Powershell不应该等待Excel退出要继续执行,相反,我需要excel保持打开状态才能继续执行Powershell。

我还知道 start-sleep 命令并不适合我的情况,因为刷新结束没有固定的时间值,每个文件都有它的时间,而且每月的每个周期都有它的时间(数据量)每天都会增加,直到月底)。

所以我的问题是:是否可以进行 Powershell 测试 Excel 文件是否已刷新其数据,如果是,则继续,否则会等待更长时间?

bea*_*ker 5

霰弹枪方法:

  1. Excel 具有Application.Ready属性。它应该表明 Excel 何时准备好进行自动化通信,但细节尚不清楚。尝试这样的事情:

    $Excel = New-Object -ComObject Excel.Application
    
    # Do your stuff here
    
    # Wait for Excel to became ready
    while (!$Excel.Ready)
    {
        Start-Sleep -Seconds 1
    }
    
     # Do other stuff
    
    Run Code Online (Sandbox Code Playgroud)
  2. QueryTable 具有刷新属性。尝试这个:

    $Excel = New-Object -ComObject Excel.Application
    $Workbook = $Excel.Workbooks.Open('C:\Path\To\Workbook\Data.xlsx')
    
    # Are any of the QueryTables refreshing?
    # Don't have Excel right now, so expression below might need some tweaking
    While (($Workbook.Sheets | ForEach-Object {$_.QueryTables | ForEach-Object {if($_.QueryTable.Refreshing){$true}}}))
    {
        Start-Sleep -Seconds 1
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. ODBCConnection 有Refreshing属性。试试这个:

    $Excel = New-Object -ComObject Excel.Application
    $Workbook = $Excel.Workbooks.Open('C:\Path\To\Workbook\Data.xlsx')
    
    # Is ODBCConnection refreshing?
    # Don't have Excel right now, so expression below might need some tweaking
    While ($Workbook.ODBCConnection.Refreshing)
    {
        Start-Sleep -Seconds 1
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 也许这 5 个文件的PivotCache.BackgroundQueryODBCConnection.BackgroundQueryQueryTable.BackgroundQuery属性设置为 true?