【问题标题】:PowerShell Script to turn off "Enable background refresh" in an Excel用于在 Excel 中关闭“启用后台刷新”的 PowerShell 脚本
【发布时间】:2020-07-30 02:03:36
【问题描述】:

我有一个 PowerShell 脚本,它可以根据一组条件动态创建、更新和删除 Excel 工作簿。创建 excel 所涉及的过程之一是运行电源查询。但是,它似乎默认设置“启用后台刷新”为启用。

这会导致在运行代码的更新部分时出现问题,因为 Excel 在电源查询刷新之前打开、保存和关闭。

我这个脚本不断地创建和删除新的 Excel,所以手动关闭设置是不可行的。我能找到的唯一解决方案是添加一个睡眠功能,但是当有很多 excel 时,这会导致性能延迟。

Excel 设置:

更新代码:

    $File = Get-Item("$Path\$Set\$Set-main-$ReleaseDate.xlsx")

    $Excel = New-Object -ComObject excel.application
    $Excel.DisplayAlerts = $False
    $Excel.visible = $False
    $WorkBook = $Excel.Workbooks.Open($File.FullName)

    $WorkBook.RefreshAll()

    $WorkBook.SaveAs($File, 51)
    $WorkBook.Close($True)

    $Excel.Quit()
    [void][System.Runtime.Interopservices.Marshal]::ReleaseComObject($WorkSheet)
    [void][System.Runtime.Interopservices.Marshal]::ReleaseComObject($WorkBook)
    [void][System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
    [System.GC]::Collect()

【问题讨论】:

    标签: excel powershell


    【解决方案1】:

    也许这些可以为您提供指导。

    您可以在工作表中添加一个宏(加载一个事件),它可以在本机上执行此操作,for example, this

    Dim lCnt As Long
    
        'The following code loops through all connections
        'in the active workbook.  Change the property to
        'True to Enable, False to Disable background refresh.
        
        With ActiveWorkbook
            For lCnt = 1 To .Connections.Count
              'Excludes PowerPivot and other connections
              If .Connections(lCnt).Type = xlConnectionTypeOLEDB Then
                .Connections(lCnt).OLEDBConnection.BackgroundQuery = False
              End If
            Next lCnt
        End With
        
    End Sub
    

    More VBA examples here.

    但您的问题也可能被视为此 SQ Q&A 的重复 Refreshing Excel Sheets using PowerShell

    这里: Make PowerShell Wait for Excel to Finish Refreshing Pivot Table

    $sheet.Calculate()
    $null = $sheet.QueryTables.QueryTable.Refreshing
    
    Excel has Application.Ready property. It should indicate when Excel is ready for automation communication, but details are unclear. Try something like this:
    

    以及此处的另一个讨论,与您的用例相关。 Refreshing Excel connections with Powershell

    唯一的其他选择是在每个与您使用的睡眠方法之前使用进程等待。

    【讨论】:

      猜你喜欢
      • 2019-05-31
      • 2022-09-24
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      • 1970-01-01
      • 2012-09-03
      相关资源
      最近更新 更多