gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:44:47 25 4
gpt4 key购买 nike

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

最佳答案

霰弹枪方法:

  1. Excel 有 Application.Ready属性(property)。它应该表明何时Excel 已准备好进行自动化通信,但是 details areunclear 。尝试这样的事情:

    $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. 查询表有 Refreshing属性(property)。试试这个:

    $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.BackgroundQuery , ODBCConnection.BackgroundQueryQueryTable.BackgroundQuery属性设置为 true?

关于excel - 让 PowerShell 等待 Excel 完成刷新数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28582443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com