How to check whether Connection Refresh was successful

前端 未结 2 1288
盖世英雄少女心
盖世英雄少女心 2020-12-18 11:31

In Excel 2016 VBA, I\'m refreshing several queries like this:

MyWorkbook.Connections(MyConnectionName).Refresh

After the code is done, and

2条回答
  •  眼角桃花
    2020-12-18 12:16

    Just found this solution at Execute code after a data connection is refreshed

    The bottom line is: Excel refreshes data connection in the background and thus the rest of the code is executed without interruption.

    Solution: set BackgroundQuery property to False

    Example:

    For Each cnct In ThisWorkbook.Connections
       cnct.ODBCConnection.BackgroundQuery = False
    Next cnct
    

    Possible problem: don't know which connection it is...

    Remedy: case... when...

    Dim cnct as WorkbookConnection ' if option explicit
    ' ODBC and OLE DB
    For Each cnct In ThisWorkbook.Connections
       Select case cnct.type
          case xlconnectiontypeodbc
       cnct.ODBCConnection.BackgroundQuery = False
          case xlconnectiontypeoledb
        cnct.OledbConnection.BackgroundQuery = False
       end select
    Next cnct
    

    As you can see, code above only deals with ODBC and OLE DB. Depending on what types of data connection you are using, you can expand the select case clause. Unless changed, once run, connection's BackgroundQuery will remain off.

提交回复
热议问题