Search code examples
ms-accessvbams-access-2007

Not getting query results back


My query does not return any values even though the table has the records. I am trying to retrieve an employeed id based on the name entered. I keep getting the message "No employee id". I am a new learner as far as Access VBA is concerned. I have worked with Access tables and other tables without issues. I did validate that the form field has the correct value and is being captured in the variable strEmpName

    Set cnn1 = New ADODB.Connection
    mydb = "C:\accesssamp\Documents\Tasks.accdb"
    strCnn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & mydb
    cnn1.Open strCnn

    'This statement added here just to indicate that I am getting the value
    strEmpName = cboEmployeeName.Text ' Getting employee name from form field

    Set cmd = New ADODB.Command

    With cmd
        .ActiveConnection = CurrentProject.Connection
        .CommandText = "SELECT [EmployeeId] FROM [Employees] " & _
                        "WHERE [EmployeeName] = [strEmpName]"
        .CommandType = adCmdUnknown
        .Parameters.Append cmd.CreateParameter( _
                    "[strEmpName]", adChar, adParamInput, 50)
        .Parameters("[strEmpName]") = strEmpName
    End With

    ' Execute the Query and return the employeeId
    Set rstEmp = cmd.Execute

    If rstEmp.RecordCount < 1 Then
        MsgBox "No Employee Id"
    Else
        MsgBox rstEmp(0).Value
    End If

Solution

  • Your sample had multiple issues. I'm unsure whether this is exactly what you want, but it works without error on my system.

    With cmd
        '.ActiveConnection = CurrentProject.Connection
        .ActiveConnection = cnn1
        .CommandText = "SELECT [EmployeeId] FROM [Employees] " & _
                        "WHERE [EmployeeName] = [strEmpName]"
        .CommandType = adCmdUnknown ' or adCmdText; either works
        .Parameters.Append cmd.CreateParameter( _
                    "strEmpName", adVarChar, adParamInput, 255, strEmpName)
    End With
    
    ' Execute the Query and return the employeeId
    Set rstEmp = cmd.Execute
    
    'If rstEmp.RecordCount < 1 Then
    If rstEmp.BOF And rstEmp.EOF Then
        MsgBox "No Employee Id"
    Else
        MsgBox rstEmp(0).value
    End If
    

    Notes:

    1. I assumed you want to run your query from the cnn1 connection to that other database instead of from CurrentProject.Connection.
    2. Supply a compatible data type for CreateParameter. And for a text parameter, supply a value for its maximum length. Finally include the value for the parameter.
    3. rstEmp.RecordCount was returning -1, which is less than 1, so your code displayed "No Employee Id" even when the recordset was not empty. Instead of checking RecordCount, check whether the recordset is empty.