I am trying to connect to MySQL using VBA, in order to write the results produced in Excel. I need to write thousands of rows each containing around 100 columns. So I have created separate subroutines to connect to MySQL before I start writing the results, then for each row, I need to run an 'insert' query and in the end, I need to close the connection.
I have created the following subs which I am calling from my main program:
sub main
dbconnect
for i = 1 to 50000
dbupdate
next i
dbclose
sub dbconnect()
Dim cn as ADODB.connection
Set cn = New ADODB.Connection
cn.open "Driver .............." (usual stuff)
sub dbupdate()
dim sqlstr as string
sqlstr = "insert into table " .... (some query to write the results in a table)
cn.execute sqlstr
sub dbclose()
cn.close
cn = nothing
However, my macro doesn't seem to understand cn when it appears in the dbupdate or dbclose subroutines. It seems that the connection I had set up in dbconnect is not accessible to other subroutines. The macro stops at cn.execute sqlstr in dbupdate with the following error: runtime error 91: object variable or with block variable note set.
Is there a way I can make this work?
Many thanks!