Bob P
Bob P

Reputation: 237

I get a data type conversion error when running this code

But I am sure that the data types can work together, ItemID from 1 table is AutoNumber and a number in the other table.

Private Sub Command17_Click()

Dim cmbItem As String

cmbItem = "SELECT ItemID FROM Items WHERE Items.Name = " & Me.Combo0.Value & ";"

Dim sc1 As DAO.Recordset
Set sc1 = CurrentDb.OpenRecordset("Buy", dbOpenDynaset)

sc1.AddNew
sc1.Fields("ItemID").Value = cmbItem
sc1.Fields("BuyPrice").Value = Me.Text13.Value
sc1.Fields("Notes").Value = Me.Text18.Value
sc1.Update

End Sub

Thanks in advance, Bob P

Upvotes: 1

Views: 2381

Answers (1)

HansUp
HansUp

Reputation: 97131

If this is the line which triggers your error ...

sc1.Fields("ItemID").Value = cmbItem

... notice that cmbItem is a string which contains a SELECT statment (SELECT ItemID FROM ...). And you told us "ItemID from 1 table is AutoNumber and a number in the other table". So you're attempting to assign a string value to a numeric field. Furthermore, that string can't be cast to a valid number. It has to fail.

Just guessing here, but maybe you want something like this ...

Dim cmbItem As Long
cmbItem = DLookup("ItemID", "Items", "[Name]=" & Me.Combo0.Value)

If [Name] is a text field, add quotes around the value you compare it to ...

cmbItem = DLookup("ItemID", "Items", "[Name]='" & Me.Combo0.Value & "'")

If that's close, you could rename the variable to lngItem so the code is less likely to confuse your collaborators.

If the DLookup() might return Null, consider feeding it to a Nz() expression.

Upvotes: 1

Related Questions