I am attempting to query a DB from VBA, in order to avoid such issues a SQL injection I have been told I should parametrise the SQL string of code. The code I have at the moment, which returns no error, but no result either (!) is:
Sub ImportData_Click()
Dim strSql As String
Dim strDate As String
Dim StrDatetwo As String
Dim strinfo As String
Dim strinfotwo As String
Dim strgroup As String
Dim objConn As ADODB.Connection
Set objConn = New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
'Parameters
strDate = Format(Range("Date"), "DDMMMYY")
StrDatetwo = Format(Range("Datetwo"), "DDMMMYY")
strinfo = "someinfo"
strinfotwo = "total"
strgroup = "total"
'open connection
ConnectionString = "Provider=name ;Data Source=name;Initial Catalog=name;Integrated Security=SSPI"
objConn.Open ConnectionString
'SQL string
strSql = "Declare @mindate date," & _
"@maxdate date " & _
"set @mindate ='" & strDate & _
"'; set @maxdate ='" & StrDatetwo & _
"'; SELECT MIN([results].run_id) " & _
"FROM [results] " & _
"inner join [official_run_table] on ([results].run_id=[official_run_table].run_id and [official_run_table].run_type_id='1' )" & _
" WHERE Info ='" & strinfo & _
"' and two ='" & strinfotwo & _
"' and group= '" & strgroup & _
"' AND [results].date between @mindate and @maxdate"
'MsgBox strSQL '- to check data
rst.Open strSql, objConn
If Not rst.EOF Then
Worksheets("Reference").Range("E2").CopyFromRecordset rst
rst.Close
Else
MsgBox "Error: No records returned.", vbCritical
End If
'Clean up
objConn.Close
Set objConn = Nothing
Set rst = Nothing
End Sub
No error but no result would imply no values exist in the DB for this query, but I know otherwise! It is my intention to a parametrise strinfo, strinfotwo, strgroup as well, but first I would like to get the above working. How am I getting this wrong? Thanks in advance