繁体   English   中英

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

[英]Make PowerShell Wait for Excel to Finish Refreshing Pivot Table

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

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

我也知道 start-sleep 命令对我的情况不是最好的,因为刷新结束的时间没有固定值,每个文件都有它的时间,每个月的每个时期都有它的时间(数据量每天增加,直到月底)。

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

霰弹枪进场:

  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
  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?

对我来说,这个简单的代码片段起到了作用:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM