Vba – Use Access VBA to change the record source for a form

ms-accesssubformvba

I am creating a search form and I am unable to see the search results in the subform.
The query runs fine, I have set the subforms record source to the query. I donot get any errors. When I click the search button the query runs and it shows the number of rows in the record selector at the bottom of the subform, but i cannot see the rows.

Here is my code for the OnClick event of the button:

Private Sub cmdSearch_Click()

Dim tableName As String
Dim colName As String
Dim keyword As String
Dim strSQL As String

tableName = Me.cmbTableNames.Value
colName = Me.cmbColumnNames.Value
keyword = Me.txtKeyword.Value
strSQL = "Select * from [" & [tableName] & "] where [" & [colName] & "] like '*" &  [keyword] & "*';"
Debug.Print strSQL
Me.searchResultsForm.Visible = True

Forms![F_SearchForm]![searchResultsForm].Form.RecordSource = "Select * from [" &   [tableName] & "] where [" & [colName] & "] like '*" & [keyword] & "*';"
Forms![F_SearchForm]![searchResultsForm].Form.Requery
End Sub

Can someone tell me what I am doing wrong.

Thank You

This is what shows up in the Immediate Window for Debug.Print

Select * from [dbo_Internal Contacts] where [First Name] like '*Amy*';

My Form looks like this in the form view:

enter image description here

I have added some text boxes to my subform (around 35). Now if I run the query my form looks like this:
enter image description here

How can I link these text boxes on the subform to the columns in the recordsource using vba?

Please help

Best Answer

I figured it out. Here's what I did

I modified the query to

Select * into tmpSearchResults from [" & [tableName] & "] where [" & [colName] & "] like '*" & [keyword] & "*';

And I gave the tmpSearchResults as recordsource to my subform.

I drop the tmpSearchResults table everytime the the table name combobox is updated.

It works just as I wanted it to.

Related Topic