【问题标题】:Make PowerShell Wait for Excel to Finish Refreshing Pivot Table让 PowerShell 等待 Excel 完成刷新数据透视表
【发布时间】:2015-04-19 09:14:27
【问题描述】:

所以我开发了一个 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 文件是否已刷新其数据,如果是,它会继续,否则它会等待更长时间?

【问题讨论】:

    标签: excel vba powershell


    【解决方案1】:

    霰弹枪方法:

    1. Excel 具有Application.Ready 属性。它应该表明何时 Excel 已准备好进行自动化通信,但 details are unclear。试试这样的:

      $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
      
    2. QueryTable 具有Refreshing 属性。试试这个:

      $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
      }
      
    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
      }
      
    4. 也许这 5 个文件的 PivotCache.BackgroundQueryODBCConnection.BackgroundQueryQueryTable.BackgroundQuery 属性设置为 true?

    【讨论】:

    • 感谢您的回答。好吧,我尝试了您的解决方案,但我仍然有 vba 错误 1004。
    • 非常感谢您的解决方案。我将测试 ODBCConnection.Ready,但我认为它与这篇帖子 stackoverflow.com/questions/181585/… 有关,因为当我取消宏运行的部分时,出现了帖子中描述的错误。
    • 对我来说,#1 只是导致 Excel 挂起,但在尝试从 CSV 刷新时,第 2 项工作
    【解决方案2】:

    对我来说,这个简单的代码-sn-p 成功了:

    $sheet.Calculate()
    $null = $sheet.QueryTables.QueryTable.Refreshing
    

    看起来只要获取 Refreshing-Attribute 就足以等待刷新/计算周期结束。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-30
      • 2012-08-03
      • 1970-01-01
      • 2015-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多