Forum Discussion

Garry Alweyn's avatar
Garry Alweyn
Copper Contributor
Oct 14, 2017
Solved

Can I Automate an ODBC connection Refresh AND then save workbook by a scheduled task?

Hi Community,   I am using an excel workbook to grab data from an accounting system via an ODBC32 bit connection.   Is there a way to schedule these ODBC connections inside the workbook to refres...
  • JKPieterse's avatar
    Oct 16, 2017
    In the queries properties you can set a scheduled refresh time. But a scheduled saving time must be done using a bit of VBA code. Best to combine this with the refresh rather than scheduling that refresh. In a normal module:

    Option Explicit

    Dim mdNextTime As Double

    Sub Unschedule()
    'Prevent error in case nothing was scheduled
    On Error Resume Next
    'Unschedule pending ontime proc
    Application.OnTime mdNextTime, "UpdateRoutine", , False
    End Sub

    Sub UpdateRoutine()
    'Update routine goes here
    ThisWorkbook.Worksheets("Sheet1").ListObjects(1).QueryTable.Refresh False
    ThisWorkbook.Save
    mdNextTime = Now + TimeValue("00:10:00")
    Application.OnTime mdNextTime, "UpdateRoutine"
    End Sub
    In your ThisWorkbook module:
    Option Explicit

    Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Unschedule
    End Sub

    Private Sub Workbook_Open()
    UpdateRoutine
    End Sub

Resources