简体   繁体   中英

Run SQL Select query from .sql file using VBA in Excel

To create dynamic select statements I am currently creating a temp file to hold the query (30k + characters due to number of joins and decodes being used). I'd like to use this temp file that has the full select statement to return the data into excel.

Using my current code I can only run a short select statements. The strings I create seem to get truncated for some reason.

Here's the snippet of code I'm using that creates the file and currently attempts to run the same string.

' Set file details
fileDir = "C:\temp\"
filePath = "C:\temp\" & node & "_SRO_TCs.sql"

'check if directory exists, if not create it
If Dir(fileDir, cbDirectory) = "" Then
MkDir fileDir
End If

' open the file
Open filePath For Output As #1

'Write to file
outputText = sqlQuery3
Print #1, outputText

'open connection
sqlCon.ConnectionString = Conn
  'Cn.CursorLocation = adUseClient
sqlCon.Open

'set and execute sql command
Set sqlCommand.ActiveConnection = sqlCon
sqlCommand.CommandText = sqlQuery3
sqlCommand.CommandType = adCmdText
sqlCommand.Execute

'open recordset
Set sqlRecordSet.ActiveConnection = sqlCon
sqlRecordSet.Open sqlCommand


'copy data to excel
ActiveSheet.Range("A1").CopyFromRecordset (sqlRecordSet)  <<<< This is where i get an error returned when stepping through the code - "Run-time error '91': Object variable or With block variable not set"

'close connections
sqlRecordSet.Close
sqlCon.Close

'Close file
Close #1

When I check the file created it has a working sql select statement. I'd like to be able to run this file or the string. Please help!

The Command Execute method looks like this

Set recordset = command.Execute( RecordsAffected, Parameters, Options )

Your code is quite different. Hadn't looked too hard at your code before, because you said it worked with a shorter SQL statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM