Question

I've been trying to create a macro that is run via a batch file to generate a report and have been having some massively annoying issues with connecting to a SQL Server, probably due to some stupid mistake on my part.

My code to create a connection is as follows:

Dim dbs As Database
Dim qdf As QueryDef
Dim rst As Recordset

Set dbs = OpenDatabase("", False, False, connect)
Set qdf = dbs.CreateQueryDef("")

where 'connect' is a string containing connection details.

My problem is that Excel (2007) seems to have a problem with the very last line of that block, for whatever reason. I've added a watcher to the dbs variable, and it seems perfectly fine, so then why does it not like qdf?

The even stranger thing is that, if I put a 'Stop' command at the very beginning of the macro, start execution from the batch file, and then continue manually upon reaching the Stop, it works perfectly and does exactly what I'd like it to.

I've tried looking at DBEngine.Errors, and that tells me that I have the following problems:

  • General error: Invalid window handle
  • Connection not open

Again, this makes no sense to me, especially given that it works under manual execution, and Google hasn't yielded any answers.

P.S. If this is unclear, please also take a look at this question, which seems to be asking the same thing, but has no answer.

Was it helpful?

Solution

So, using the scientific method, a co-worker and I were able to figure out what the issue was, though I have no idea how it makes sense or why it would even be an issue in the first place. The layout of the macro was, in a rough sense, as follows:

  • Test database connection and close it
  • Create new workbook
  • Connect to database again and populate workbook from database calls

For some reason, however, the solution ended up being that VBA didn't like the fact that we were doing connection stuff both before and after creating the workbook. Changing the program flow to:

  • Create new workbook
  • Test database connection and close it
  • Connect to database again and populate workbook from database calls

did the trick. Again, I have no clue why this solved our problem, or if changing the order of this sequence changed something more significant within the code, but it works now! If anyone has any ideas as to why this might be, feel free to comment.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top