Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make an ADODB.Connection Persistent in VBA in Excel?

I have an Excel spreadsheet that needs to display data from our SQL database.

I am storing the results of a slow query in a temporary table and want to be able to access those results repeatedly without having to rerun the slow query.

I am using an ADODB.Connection in VBA to connect to our SQL database and retrieve information. I want to open a connection once and use that session across various macros for as long as the user is using the spreadsheet. I can't find any way to make the connection persistent, so it always closes once I exit the macro that opened it and I lose any temporary tables that I created.

like image 352
Matt Victory Avatar asked Jul 10 '11 17:07

Matt Victory


People also ask

What is Adodb VBA?

An ADODB Recordset in VBA is a storage item: you can store all kinds of different things in it: numbers, texts, dates. An ADODB Recordset is a database that you can design, fill and edit completely in the working memory. VBA has several other options for storing data: - a dictionary. - a collection.

What reference is needed for Adodb connection?

To reference ADO from Microsoft Access Verify that at least the following libraries are also selected: Visual Basic for Applications. Microsoft Access 8.0 Object Library (or later) Microsoft DAO 3.5 Object Library (or later)


1 Answers

Daz Lewis is entirely correct that you shouldn't be keeping database connections open indefinitely. However, if this is a local database and you're the only one using it, then you should be able to keep it open as long as you please.

Add this as the top line of the module holding your code:

Global dbConnPublic As ADODB.Connection

In the "ThisWorkbook" object:

Private Sub Workbook_Open()
    Set dbConnPublic = openDBConn() 'Or whatever your DB connection function is called'
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
    dbConnPublic.Close
End Sub

This will open the db connection on opening the workbook and will close it on closing the workbook. Keep in mind you may want to check to make sure the connection is still open whenever you need to use it as it could get closed by the server if it's open for too long.

like image 131
Kevin Pope Avatar answered Oct 19 '22 22:10

Kevin Pope