0

I have Mysql query through VBA and having error when i used date from cell . I need to use cell value for looping purpose. I think its due to date format compatibility between excel and Mysql. Appreciate your help. Thanks!

For R = 6 to lastrow

SQLQuery2 = "SELECT * FROM Mfg.databasemodels_note where typeId = " & Sheets("Sheet1").Range("B" & R) & " AND date < " & Sheets("Sheet1").Range("I" & R) & " order by date asc limit 1;"
Community
  • 1
  • 1
Kaison
  • 33
  • 7

1 Answers1

0

Short answer is that your sql string contains a date that's unrecognizable to MySQL. Put a breakpoint just after building the string, run the code, then look at the content of the string; how's MySQL supposed to make sense of it?

As per MySQL reference material (link below), here's your updated line of code:

SQLQuery2 = "SELECT * FROM Mfg.databasemodels_note where typeId = " & Sheets("Sheet1").Range("B" & R).Value & " AND date < " & Format(Sheets("Sheet1").Range("I" & R).Value, "'YYYY-MM-DD Hh:NN:SS'") & " order by date asc limit 1;"

Real answer is that you never, ever want to build a SQL string containing user input, from scratch, because of SQL injection risks. Read How To Invoke a Parameterized ADO Query Using VBA/C++/Java for a quick overview of what you should be doing (on top of running your own basic validation).

Reference material: MySQL 5.7: The DATE, DATETIME, and TIMESTAMP Types / Visual Basic for Applications: Format Function

Further reading: VBA, ADO.Connection and query parameters / ADODB Command failing Execute with parameterised SQL query

Excelosaurus
  • 2,789
  • 1
  • 14
  • 20