Domanda

I have a simple access form with an unbound textbox that is used to search for records with a matching date, with the results displayed in a subform. The backend database is stored in an SQL Express 2008 instance, accessed via an ODBC connection (SQL Server Native Client 10.0). The client is Access 2007, running on 64 bit Windows 7 professional.

When the user clicks on the search button on the form, the following VBA code is executed to update the subform.

Private Sub UpdateSfmQuery()
    Dim query As String

    If IsDate(txtDate.Value) And IsNumeric(cboStaff.Value) Then
        query = "SELECT * FROM TimesheetEntries " & _
                "WHERE StaffId = " & cboStaff.Value & " " & _
                "AND [Date] = '" & _
                Format(txtDate.Value, "YYYY/MM/DD HH:MM:SS") & "' "
    Else
        query = "SELECT * FROM TimesheetEntries WHERE 0 = 1;"
    End If

    frmTimesheetUpdateSfm.Form.RecordSource = query  '<--- Fails here
End Sub

The datatype in the SQL Server back end [Date] field is DateTime, and the code above fails on the highlighted line above with the error, Data type mismatch in criteria expression.

I've tried changing the format property of txtDate from short date to general date, and I've also modified the date format in the line above that formats txtDate.Value.

The SQL query contained in the variable query in the above code excerpt (value shown below), executes perfectly when copied and pasted into SQL Express Management Studio.

SELECT * FROM TimesheetEntries WHERE StaffId = 14 AND [Date] = '2011/11/22 00:00:00'

What am I doing wrong?

È stato utile?

Soluzione

The problem is that date values inside native Access queries need to be surrounded by pound/hash signs instead of quotes. Basically, like any SQL database, Access has it's own dialect of SQL and it is slightly different from SQL Server.

Private Sub UpdateSfmQuery()
    Dim query As String

    If IsDate(txtDate.Value) And IsNumeric(cboStaff.Value) Then
        query = "SELECT * FROM TimesheetEntries " & _
                "WHERE StaffId = " & cboStaff.Value & " " & _
                "AND [Date] = #" & _
                Format(txtDate.Value, "YYYY/MM/DD HH:MM:SS") & "# "
    Else
        query = "SELECT * FROM TimesheetEntries WHERE 0 = 1;"
    End If

    frmTimesheetUpdateSfm.Form.RecordSource = query  '<--- Used to fail here
End Sub

Remember, you can always take a mockup of your query and use Access's query editor to try to make the query work.

As a side note, I recommend you tag questions like this with the ms-access tag unless your problem is specific to a certain version of Access.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top