Pangu
Pangu

Reputation: 3819

How to find a record with an empty field value using VBA in Access?

I'm a bit confused on how exactly VBA views empty field values in a table/datasheet because I'm trying to use Recordset.FindFirst method to locate a record within my datasheet, but if the record contains a field that is empty, it cannot locate the record.

For example, here's what my table may look like:

FieldOne   FieldTwo
123        SomeName1
456        
789        SomeName2

For record 456, the value in FieldTwo is empty. The datatype for FieldOne and FieldTwo is a Short Text.

Assume myDatasheet is linked to the above table with those mentioned records.

I attempt to find the record 123 like so:

Dim crit As String
crit = "FieldOne = '" & Me.textBoxOne & "' And " & _
       "FielTwo = '" & Me.textBoxTwo & "'"

With myDatasheet.Form
    .RecordsetClone.FindFirst crit 

    If Not .RecordsetClone.NoMatch Then
        MsgBox "FOUND"
    Else
        MsgBox "NOT FOUND"
    End If
End With  

Where the value in Me.textBoxOne is 123 and in Me.textBoxTwo is SomeName1 and I get a FOUND.

However, if I try to find record 456 using Me.textBoxOne as 456 and Me.textBoxTwo as "", I get a NOT FOUND.

There's got to be something syntactically wrong with my code. What should the correct criteria be?

Thanks.

Upvotes: 0

Views: 1887

Answers (1)

Erik A
Erik A

Reputation: 32642

Null is not the same as an empty string. Your "empty" field likely is Null, and comparing Null to any string resuts in Null, which gets parsed as False.

While you can add some logic to check if your form field is null or an empty string, and then use Is Null in the condition, like KostasK suggests, there's a simple workaround: just concatenate an zero-length string to your field. That will cause Null values to become zero-length strings, making them pass the comparison:

crit = "FieldOne = '" & Me.textBoxOne & "' And " & _
       "FielTwo & '' = '" & Me.textBoxTwo & "'"

Note that this will invalidate any indexes, which might lead to performance issues in very select situations.

Upvotes: 1

Related Questions