1

I want to run an SQL query from excel to Access as shown below. When I run the code, I get an "Incompatible data type in criterion expression" error. Do you have a tip, please, to get me out of this?

Regards

Sub test()
  Dim myDate As Date
  Dim myCUID As String
  Dim i As Long
  Dim cnt As Object, rst As Object

  Set rst = CreateObject("ADODB.Recordset")
  Set cnt = CreateObject("ADODB.Connection")

  strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & ThisWorkbook.Path & "\ATD_monitoring_basePro.accdb';"

  'Open connection to the database
  cnt.Open strConnection

  'Begin transaction processing
  cnt.BeginTrans

  myDate = WorkSheets("Bla").Range("A1").Value
  myCUID = "XXXX1234"
  sqlCmd = "SELECT COUNT(*) FROM Table1 WHERE Date= '" & myDate & "' AND CUID='" & myCUID & "';"
  rst.Open sqlCmd, cnt

  'Close the ADO objects
  cnt.Close
  Set rst = Nothing
  Set cnt = Nothing
  On Error GoTo 0

End Sub
4
  • maybe WHERE [Date] Also, what is myDate being returned as? Commented Apr 14, 2021 at 7:26
  • 1
    In Access "Date" field is also string? from my view you probably in Access have normal date format, and now you trying to compare string vs date. Commented Apr 14, 2021 at 7:45
  • @Nathan_Sav. myDate retrieves a value from a range with the Date category of type "*14/03/2012". The problem arose when I changed the text range to Date. it worked well before Commented Apr 14, 2021 at 7:48
  • @Bankeris. In Access Date field is also in Date format not in String. Commented Apr 14, 2021 at 7:50

1 Answer 1

1

In Access, dates must be wrapped with # and formatted mm/dd/yyyy.

Try this:

sqlCmd = "SELECT COUNT(*) FROM Table1 WHERE [Date]= #" & _
          Format(myDate, "mm/dd/yyyy") & "# AND CUID='" & myCUID & "';"

Debug.Print sqlCmd
Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks. it works much better like that. This one I will remember well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.