VBA Open Workbook, Refresh Query, Save and Close

paddyk

New Member
Joined
May 14, 2013
Messages
6
Hi,

I am completely new to VBA and to be honest I don't really know what I am doing. I've pieced the below code together but It doesn't run when the workbook is opened, and if I start it manually it saves and closes before the query refresh is completed. Where am I going wrong? Aim is to open the excel file using a batch file and windows task scheduler, refresh the query, save the file and close.

VBA Code:
Sub Workbook_Open()
    Call RefreshQuery
    ActiveWorkbook.Save
    If Application.Workbooks.Count = 1 Then
        Application.Quit
    Else
        ActiveWorkbook.Close
    End If
End Sub

Sub RefreshQuery()
'
' RefreshQuery Macro
'

'
    ActiveWorkbook.Connections("Query").Refresh
    
End Sub
 

Some videos you may like

Excel Facts

Fastest way to copy a worksheet?
Hold down the Ctrl key while dragging tab for Sheet1 to the right. Excel will make a copy of the worksheet.

EXCEL MAX

Active Member
Joined
Nov 11, 2020
Messages
292
Office Version
  1. 2007
Platform
  1. Windows
I suppose that query have no time to be uploaded before macro close workbook.
Try to use OnTime method.
Application.OnTime Now + TimeValue("00:00:05"), "my_Procedure"
Try to create procedure in Module1 called "RefreshQuery"



VBA Code:
Sub Workbook_Open()

    ActiveWorkbook.Connections("Query").Refresh
    ActiveWorkbook.Save
    Application.OnTime Now + TimeValue("00:00:05"), "RefreshQuery"

End Sub

Sub RefreshQuery()

    If Application.Workbooks.Count = 1 Then
        Application.Quit
    Else
        ActiveWorkbook.Close
   End If

End Sub
 

Watch MrExcel Video

Forum statistics

Threads
1,122,471
Messages
5,596,345
Members
414,060
Latest member
hermanseck

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Top