Powershell excel refresh fails with "Call Was Rejected by Callee" when .visible=$false Powershell excel refresh fails with "Call Was Rejected by Callee" when .visible=$false powershell powershell

Powershell excel refresh fails with "Call Was Rejected by Callee" when .visible=$false


It seems that RefreshAll() doesn't wait for the refresh to actually succeed in the background with Visible = $False set.

Introduce an artificial delay between RefreshAll() and Save(), like so:

$excelworkbook.RefreshAll();Start-Sleep -Seconds 30$excelworkbook.Save();

Alternatively, you might be able to force the RefreshAll() to execute synchronously by setting BackgroundQuery = $False on all query tables in your workbook, as suggested in this answer to a similar question:

foreach ($Sheet in $excelworkbook.Worksheets) {    foreach ($QTable in $Sheet.QueryTables) {        $QTable.BackgroundQuery = $false    }}


I would add a DoEvents block:

[System.Windows.Forms.Application]::DoEvents() 

This will allow the queue to cycle through anything you've told Excel to do & then back to the script execution. Another thing would be to set UserControl = false so that Excel is not simply hidden, but is clearly out of the user's ability to respond to events.

Lastly, there may be something about setting Visible after you've set other properties - it may be the case that Excel responds to the Visible event by toggling a few other things (don't remember off-hand, but something in the back of my brain says this is the case, or used to be).