Reputation: 33
I've got an Access form connected to a query that's based on the input from 3 different boxes. If box1 is filled, it needs to hold true for the subsequent boxes but can be ignored if empty. The other two boxes (box2 and box3) can either have data or be empty and if empty should be ignored.
To use a broad example, if I'm searching for books contained within a library system that has 5 different libraries, I want to either select all the books within a specific library by John Doe and Jane Deer or the books by John Doe and Jane Deer held at all libraries or just books by Jane Deer, etc.
I'd been trying to follow what's described here, and it works unless I leave any of the input fields empty.
WHERE ((tblBooks.LibraryName LIKE [Forms]![frmSearchAuthors]!Box1 & "*") OR ([Forms]![frmSearchAuthors]!Box1 IS NULL))
AND (((tblBooks.Author Like "*" & [Forms]![frmSearchAuthors]!Box2 & "*") OR ([Forms]![frmSearchAuthors]!Box2 IS NULL))
OR ((tblBooks.Author Like "*" & [Forms]![frmSearchAurthors]!Box3 & "*") OR ([Forms]![frmSearchAuthors]!Box3 IS NULL)))
Alternatively, I have also tried using an IIF statements but couldn't figure out how to ignore any boxes that were left empty.
WHERE (tblBooks.LibraryName Like [Forms]![frmSearchAuthors]!Box1 & "*" OR [Forms]![frmSearchAuthors]!Box1 IS NULL)
AND (IIF (ISNULL([Forms]![frmSearchAuthors]!Box2), (tblBooks.Author IS NULL), (tblBooks.Author Like "*" & [Forms]![frmSearchAuthors]!Box2 & "*"))
OR IIF (ISNULL([Forms]![frmSearchAuthors]!Box3), (tblBooks.Author IS NULL), (tblBooks.Author Like "*" & [Forms]![frmSearchAuthors]!Box3 & "*")))
Is there something wrong with my syntax or is there another way I should be doing this?
Upvotes: 1
Views: 640
Reputation: 27644
The linked technique only works if all search boxes have the same "rank" and are combined with AND.
If you look logically, the whole author block is combined with OR, so each empty search box in there will make the whole block TRUE.
So in your case you need to build the search string with VBA, pseudo code:
for i = 1 to n
if not isnull(authorsearchbox(i)) then
strSearch = StrAppend(strSearch, CSql(authorsearchbox(i)), " OR ")
end if
next i
'-------- with --------
' Append sAppend to sBase, use sSeparator if sBase wasn't empty
Public Function StrAppend(sBase As String, sAppend As Variant, sSeparator As String) As String
If Len(sAppend) > 0 Then
If sBase = "" Then
StrAppend = Nz(sAppend, "")
Else
StrAppend = sBase & sSeparator & Nz(sAppend, "")
End If
Else
StrAppend = sBase
End If
End Function
and
CSql
Upvotes: 1