Search code examples
vbams-access

Set the FilterOn property in form_open


I want to set a filter of an continuous form in Access VBA.

Private Sub Form_Open(Cancel As Integer)
      
    Dim filter As String
    filter = "1 = 0"  ' "1=0" is just for testing purpurses
    Me.filter = filter
    Me.FilterOn = True
    Debug.Print Me.FilterOn & "; " & Me.filter


end sub

The output is:

False; 1 = 0

and the filter is not used.

Is there a way to set and activate the filter before the form is shown?


Solution

  • I found out that the reason is. I use a framework where I set the recordsource later. While there is no recordsource, "Me.FilterOn = True" simply does not work. The following code does work:

    Private Sub Form_Open(Cancel As Integer)
      
      Me.RecordSource = "select * from MyTable"
      
      Dim filter As String
      filter = "1 = 0"  ' "1=0" is just for testing purpurses
      Me.filter = filter
      Me.FilterOn = True
      Debug.Print Me.FilterOn & "; " & Me.filter
    
    end sub
    

    and the output is:

    True; 1 = 0