I'm trying to use a VBA code to pull out data from a SQL Server database. I'm having an issue with holding a Recordset object with a more complicated SQL query. Once I use a simple SQL SELECT statement everything works fine, but when declare variables (for example) I get a Run-time error on the line with .Cells(2, 1).CopyFromRecordset record_set because the record_set is empty. I keep the SQL statement in an .txt file, because the original version is about 100 lines long. Below just an example.
Here is my VBA code:
Option Explicit
Sub db_sql()
Dim conn As New ADODB.Connection
Dim record_set As New ADODB.Recordset
Dim sConnect As String
Dim sqlQry
sqlQry = read_sql("C:\Users\Desktop\test_sql.txt")
sConnect = "Driver={SQL Server};Server=FOO; Database=BAR;Trusted_Connection=yes;"
conn.Open sConnect
Set record_set = New ADODB.Recordset
record_set.Open sqlQry, conn
With Worksheets("SQL_data")
.Cells.ClearContents
.Cells(2, 1).CopyFromRecordset record_set
End With
record_set.Close
conn.Close
Set record_set = Nothing
End Sub
Function read_sql(txt_path As String) As String
Dim text As String, text_line As String
Open txt_path For Input As #1
Do While Not EOF(1)
Line Input #1, text_line
text = text & text_line & vbLf
Loop
Close #1
read_sql = text
End Function
Here is the shortened SQL statement in the "test_sql.txt":
DECLARE @date_from DATETIME
DECLARE @date_to DATETIME
SET @date_from = '2020-02-11 06:00'
SET @date_to = '2020-02-12 18:00'
SELECT TOP (1000) * FROM [FOO_DATABASE].[dbo].[BAR_TABLE] where DATESTAMP between @date_from and @date_to
Any ideas how to fix my code?