From Excel VBA i connect to MySQL to fetch my_stored_procedure. Working fine except that when I use date filter as parameters to pass to MySQL SP i receive a run-time error.
The date filters are entered by the user in two cells as start-date and end-date. The cells are defined defined as ranges dateFrom and dateTo.
So I'm using these ranges to pass on to mySql rs, but VBA throws back:
Run-time error '-2147217900 (80040e14)'
You have an error in MySQL syntax; check the manual that corresponds to your MYSQL server version... 'my_stored_procedure '2015-10-01', '2015-10-30'' at line 1.
Below is my VBA code:
Const ConnStr As String = "Driver={MySQL ODBC 5.3 ANSI Driver};Server=0.0.0.0;Database=db;User=user;Password=pw;Option=3;PORT=3306;Connect Timeout=20;"
Function MySqlCommand(strSql As String) As Variant
Dim conMySQL
Set conMySQL = CreateObject("ADODB.Connection")
Set cmd = CreateObject("ADODB.Command")
conMySQL.ConnectionString = ConnStr
conMySQL.Open
Set cmd.ActiveConnection = conMySQL
cmd.CommandText = strSql
ReturnValue = cmd.Execute
conMySQL.Close
End Function
Function MySqlRS(strSql As String) As ADODB.Recordset
Dim conMySQL
Set conMySQL = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
conMySQL.ConnectionString = ConnStr
conMySQL.Open
Set rs.ActiveConnection = conMySQL
rs.Open strSql
Set MySqlRS = rs
End Function
_____
Public Sub fetchReport()
Dim rs As ADODB.Recordset
Set rs = MySqlRS("my_stored_procedure '" & Format(Range("dateFrom"), "yyyy-mm-dd") & "' ,'" & Format(Range("dateTo"), "yyyy-mm-dd") & "' ")
Dim hd As Integer
If Not rs.EOF Then
For hd = 0 To rs.Fields.Count - 1
Worksheets("data").Cells(1, hd + 1).Value = rs.Fields(hd).Name 'insert column headers
Next
Sheets("data").Range("A2").CopyFromRecordset rs 'insert data
Sheets("data").Range("A1").CurrentRegion.Name = "rsRange" 'set named range for pivot
End If
ActiveWorkbook.RefreshAll
End Sub
And here is my SP syntax:
CREATE DEFINER=`user`@`%` PROCEDURE `my_stored_procedure`
(
in fromDate date,
in toDate date
)
BEGIN
SELECT ...
WHERE dateColumn >= fromDate AND dateColumn <= toDate
END
Any help is appreciated.
Joel
