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.
Your connection is going out of scope when the macro completes and therefore closing. You don’t want to be holding connections open indefinitely against the SQL Server as this can seriously affect performance of the database for other users/services.
How big is the data you’re storing in the temp table? If it’s not too big you could hold it locally. To prevent this data from also going out of scope when the macro completes you’ll need to store it in a module level variable rather than within the macro. Yes you could store your connection here too but I’d strongly recommend you don’t.