Microsoft 365 Excel VBA Application.CalculateUntilAsyncQueriesDone

  Kiến thức lập trình

I am trying to automate Excel query refresh reports and Excel keeps looping over Application.CalculateUntilAsyncQueriesDone.

My goal is to have VBA open the excel report, refresh it, then save it.

Office Version: – Microsoft® Excel® for Microsoft 365 MSO (Version 2302 Build 16.0.16130.20894) 64-bit.

Is this a known bug on MSO 365?

    Sub LoopAllExcelFilesInFolder()
'To loop through all Excel files in a user specified folder and refresh power query connections

Dim wb As Workbook
Dim myPath As String
Dim MyFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & ""
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  MyFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
Do While MyFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(Filename:=myPath & MyFile)
    
    'Ensure Workbook has opened before moving on to next line of code
      DoEvents
    
    'Refresh all connections and calculate until async queries are done
    'Wait for Refresh to finish before running vba
    wb.RefreshAll
    With Application
        Application.Calculation = xlCalculationAutomatic
        Application.CalculateUntilAsyncQueriesDone
        Do Until .CalculationState = xlDone
        Loop
        Application.Calculation = xlCalculationManual
    End With
    If Not Application.CalculationState = xlDone Then
    DoEvents
    End If
    
    'Save and Close Workbook
      wb.Close savechanges:=True
      
    'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      MyFile = Dir
Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

LEAVE A COMMENT