Filter Property Example

This example uses the Filter property to create a new Recordset from an existing Recordset based on a specified condition. The FilterField function is required for this procedure to run.

Sub FilterX()

    Dim dbsNorthwind As Database
    Dim rstOrders As Recordset
    Dim intOrders As Integer
    Dim strCountry As String
    Dim rstOrdersCountry As Recordset
    Dim strMessage As String

    Set dbsNorthwind = OpenDatabase("Northwind.mdb")
    Set rstOrders = dbsNorthwind.OpenRecordset("Orders", _
        dbOpenSnapshot)

    ' Populate the Recordset.
    rstOrders.MoveLast
    intOrders = rstOrders.RecordCount

    ' Get user input.
    strCountry = Trim(InputBox( _
        "Enter a country to filter on:"))

    If strCountry <> "" Then
        ' Open a filtered Recordset object.
        Set rstOrdersCountry = _
            FilterField(rstOrders, "ShipCountry", strCountry)

        With rstOrdersCountry
            ' Check RecordCount before populating Recordset;
            ' otherwise, error may result.
            If .RecordCount <> 0 Then .MoveLast
            ' Print number of records for the original 
            ' Recordset object and the filtered Recordset 
            ' object.
            strMessage = "Orders in original recordset: " & _
                vbCr & intOrders & vbCr & _
                "Orders in filtered recordset (Country = '" & _
                strCountry & "'): " & vbCr & .RecordCount
            MsgBox strMessage
            .Close
        End With

    End If

    rstOrders.Close

    dbsNorthwind.Close

End Sub

Function FilterField(rstTemp As Recordset, _
    strField As String, strFilter As String) As Recordset

    ' Set a filter on the specified Recordset object and then 
    ' open a new Recordset object.
    rstTemp.Filter = strField & " = '" & strFilter & "'"
    Set FilterField = rstTemp.OpenRecordset

End Function

Note   To see the effects of filtering rstOrders, you must set its Filter property, and then open a second Recordset object based on rstOrders.

Note   When you know the data you want to select, it's usually more efficient to create a Recordset with an SQL statement. This example shows how you can create just one Recordset and obtain records from a particular country.

Sub FilterX2()

    Dim dbsNorthwind As Database
    Dim rstOrders As Recordset

    Set dbsNorthwind = OpenDatabase("Northwind.mdb")

    ' Open a Recordset object that selects records from a 
    ' table based on the shipping country.
    Set rstOrders = _
        dbsNorthwind.OpenRecordset("SELECT * " & _
        "FROM Orders WHERE ShipCountry = 'USA'", _
        dbOpenSnapshot)

    rstOrders.Close
    dbsNorthwind.Close

End Sub