Search code examples
sqlvbams-access

How do I locate a record in an SQL query in MS Access VBA using FindFirst?


I am building a process to store a list of parts to a set of locations. One thing I want to do is keep the database from associating the same part number more than once in a location. I have a database set up, and everything should work. However, I get an error at the FindFirst function saying "Invalid Argument". Everything looks like it should be ok according to Microsoft's documentation, so I am stumped on how to fix this problem.

Here's the portion of the code that is part of it:

    Dim db As Database
    Dim rst As Recordset
    Dim rstDup As Recordset
    Dim partNumber As String
    Dim strSQL As String
    Dim Location As String
    Location = Forms!frmCheckIn!cboLocation
    strSQL = "SELECT PartNumber FROM tblWarehouse WHERE tblWarehouse.Location='" + Location + "';"
    
    Set db = Nothing
    Set db = CurrentDb
    Set rstDup = db.OpenRecordset(strSQL)
    partNumber = tbxPartNumber
    
    'Need to add protection against duplicate part number in location.
    rstDup.MoveFirst
    rstDup.MoveLast
    rstDup.MoveFirst
    rstDup.FindFirst "partNumber"
    If rstDup.NoMatch = False Then
        MsgBox ("Part number is already in location. Place parts in location or select a new location.")
        Exit Sub
    End If

Solution

  • The FindFirst is not provided any parameter to search for. What part number do you want to find?
    rstDup.FindFirst "partNumber = '" & Me.tbxPartNumber & "'"

    But you don't even need to use FindFirst. Open recordset with Location and PartNumber filter criteria then check if recordset is empty.
    If Not rstDup.EOF Then

    Or instead of opening recordset, use DLookup(). Most of that procedure code could be replaced with:
    If Not IsNull(DLookup("PartNumber", "tblWarehouse", "Location='" & Me.cboLocation & "'")) Then