Well, I do change the recordsource successfully in two spots; and in this case I just could not get rid of an error when the recordset was nil.
However, I now found the neat solution:
Code:
Private Sub Form_Current()
'' first I am hiding or showing some buttons; then
To prevent clicking the ‘Show Details’ Button - and avoid going first or last when no sense
If Me.Recordset.RecordCount = 0 Then
Me.Button_OpensMainForm.Visible = False
Me.cmdLast.Enabled = False
Me.cmdNext.Enabled = False
Else:
Me.Button_OpensMainForm.Visible = True
So I hide it when it makes no sense using it.
And since you asked, this is the code that assembles the SQL statement:
Code:
Private Sub Search_Execute_Button_Click()
On Error GoTo Err_Search_Execute_Button_Click
' Search_Execute_Button generates and then executes the Query
' It creates a WHERE clause using search criteria entered by user and
' set RecordSource property of HyperSearch_SubForm.
ArgCount = 0 'Initialize argument count
MyCriteria = "" 'Initialize SELECT statement
MySQL = "SELECT * FROM Q_Super_Search_This WHERE "
' Use values entered in search form header to build WHERE clause.
AddToWhereTerm [Search_Field_1], "[Search_Field_1]", MyCriteria, ArgCount
AddToWhere [Search_Field_2], "[Search_Field_2]", MyCriteria, ArgCount
AddToWhereTerm [Search_Field_3], "[Search_Field_3]", MyCriteria, ArgCount
AddToWhere [Search_Field_4], "[Search_Field_4]", MyCriteria, ArgCount
AddToWhere [Search_Field_5], "[Search_Field_5]", MyCriteria, ArgCount
' -->>> If no criterion specifed, return all records
' otherwise, assemble an SQL statement.
' confirmed this 26/09/2019 - when suppressed, the SQL stmt is missing the where clause; so produces an error
If MyCriteria = "" Then
MyCriteria = "True"
MyRecordSource = MySQL & MyCriteria ' very important for Null search 26/09/2019
Else
MyRecordSource = MySQL & MyCriteria & "ORDER BY Q_Super_Search_This.Search_Field_1"
End If
Me![HyperSearch_SubForm].Form.RecordSource = MyRecordSource
' If no records match criteria, display message.
If Me![HyperSearch_SubForm].Form.Recordset.RecordCount = 0 Then
MsgBox "No entries match the criteria you entered. " & vbCrLf & "Review your criteria, then click the Find button again. ", 48, "No Entries Found"
End If
Me!Button_Clear.SetFocus
One of the two crucial subs is:
Code:
Private Sub AddToWhere(FieldValue As Variant, FieldName As String, MyCriteria As String, ArgCount As Integer)
If FieldValue <> "" Then
' Add "and" for second and subsequent criterion.
If ArgCount > 0 Then
MyCriteria = MyCriteria & " and "
End If
' Append criterion to empty or existing criteria
' Enclose FieldValue and asterisk in quotation marks
MyCriteria = (MyCriteria & FieldName & " Like " & Chr(39) & FieldValue & Chr(42) & Chr(39))
' Increase argument count.
ArgCount = ArgCount + 1
End If
End Sub
The AddToWhereTerm additionally appends an asterisk for a more flexible search.