Keith Stein
Keith Stein

Reputation: 6724

Query gives expected result in Access but not through ADODB

I'm trying to write a simple VBA function that, when given an email address, will look it up in an Access database and return the ID of the contact associated with it.

Here is the VBA code:

(There is a string variable named EmailAddress previously defined.)

    Dim Cnn As ADODB.Connection
    Dim STR As String
    
    Set Cnn = New ADODB.Connection
    Cnn.Provider = "Microsoft.ACE.OLEDB.12.0;Data Source=C:\MyDB.accdb;Persist Security Info=False"
    Cnn.Open
    
    STR = "SELECT CompanyContact.ContactID FROM CompanyContact WHERE CompanyContact.Email LIKE '*mailto:' & ? & '*'"
    
    Dim cmd As New ADODB.Command
    Dim Rec As New ADODB.Recordset
    
    cmd.Name = "GetContactID"
    cmd.CommandText = STR
    cmd.CommandType = adCmdText
    cmd.Parameters.Append cmd.CreateParameter("Email", adVarChar, adParamInput, Len(EmailAddress), EmailAddress)
    Set cmd.ActiveConnection = Cnn
    Set Rec = cmd.Execute

Note: the column CompanyContact.Email is of type Hyperlink, hence the LIKE comparison and the string concatenation with mailto:.

When I run this code, Rec.EOF is immediatly true (so, no records returned), despite the fact that a matching record does exist in the DB.

To confirm this, I copy paste the exact same query string into Access and run it. It prompts me for the value of ?, I paste in the email address, and it returns the expected ID.

Query in Access Query result in Access

I haven't had any luck debugging this. I've changed the query string to SELECT 'Test' & ? and have confirmed that the email address is being correctly passed to Access (it returns a single record with the expected result). I just don't know why the WHERE statement isn't working via ADODB, when the same statement seems to work fine directly in Access.

Upvotes: 0

Views: 71

Answers (0)

Related Questions