Wednesday, June 22, 2016

Access VBA- Filter a subform

MS-ACCESS VBA: HOW TO FILTER A SUBFORM IN DATASHEET VIEW

Suppose that a text box is placed in the main form to filter the records of subform based on Brand inputted by the user in the Search box. The user inputs data into the Search Box to get the filtered records from the subform. To achieve this filter, we use the following codes in VBE environment. The Main Form is unbounded in this example.
The first sub routine in on the Clear Filter Button to remove filter from the subform.
The second sub routine is on the text box used for search and the AfterUpdate event is executed when user submits any value in the text box.

Option Compare Database
Option Explicit

Private Sub cmdClearFilter_Click()
    Me.Text1.Value = ""
    Me.Mobiles_subform.Form.FilterOn = False
End Sub

Private Sub Text1_AfterUpdate()
    Me.Mobiles_subform.Form.Filter = ""  'Remove the old filter criteria
    Me.Mobiles_subform.Form.FilterOn = False  ' Remove the Applied Filter
    Me.Mobiles_subform.Form.Filter = "[Brand] Like'*" & Me.Text1.Value & "*'"
    Me.Mobiles_subform.Form.FilterOn = True
End Sub


Remarks: 1) Filter is provided a double quoted criteria. In case of string values, we quote the string by single or double quotes. Similarly, date values are placed between # sign. The criteria are basically WHERE clause of SQL. 2) The Main Form is unbounded so Link Master Field and Link Child Field are empty.

AFTER FILTER:


No comments:

Post a Comment

Hot Topics