I have a embeded macro in a combo box of a DB and I want to change it to vba and I tried to Convert macros to VB and it wont.... Anyway here it is:
Record: First
Where Condition: ="[EmpID] = " & Str(Nz([Screen].[ActiveControl],0))
Try using in the AfterUpdate event of combobox:
' Set filter.
Me.Filter = "[EmpID] = " & Nz(Me!NameOfYourComboBox.Value, 0) & ""
' Activate filter.
Me.FilterOn = True
Related
Got a database with a bunch of forms. One of them is my "starting page" with several buttons, each opening a form. I have entries from may years so, to make it more functional, I have a combo box on the starting page with all the years whose value I use in a code on all my buttons to filter the forms when they open. The code looks like that:
Private Sub Edit_Sale_Contract_Click()
'Opens the selected form'
DoCmd.OpenForm "new Sale Form", , , , acFormEdit
'Applies the filter'
If Forms![Main Menu].Combo10 = "All" Then
Forms![new Sale Form].FilterOn = False
Else
Forms![new Sale Form].Filter = "[crop]=" & Chr(34) & Forms![Main Menu].Combo10 & Chr(34)
Forms![new Sale Form].FilterOn = True
End If
End Sub
I also have several reports. What I am trying to do is make a form with a Tab control, each Tab holding one report. For now, I have this similar code on the On Open event of my reports:
Private Sub Report_Open(Cancel As Integer)
If Forms![Main Menu].Combo10 = "All" Then
Me.FilterOn = False
Else
Me.Filter = "[crop]=" & Chr(34) & Forms![Main Menu].Combo10 & Chr(34)
Me.FilterOn = True
End If
End Sub
This works fine so far. I open the form with a button(no filter code) and the reports open correctly in the tabs, already filtered.
The problem: When I try to to apply a secondary filter on "Name" for example with RightClick->equals"Name" it refreshes the report and does not apply it.
I tried changing the event on the reports from On Open to On Load. The second filter then applies correctly, but when I click anywhere I get Run-time error '5': Invalid procedure call or argument. Debug indicates the line
MeFilterOn = True
Closing the debugger, the second filter on the "Name" is cancelled, the first one on "Crop" is still on.
Any advice is appreciated. Please note that I am learning Access and VBA myself and I am terribly new at it. Thanks in advance
Your current code overwrites any set filter.
If you want to combine filters, you need to append your new filter to the old one:
Private Sub Report_Open(Cancel As Integer)
If Forms![Main Menu].Combo10 = "All" Then
'Do nothing, because else you would deactivate the custom filter
Else
If Me.Filter <> "" Then
Me.Filter = Me.Filter & " AND [crop]=" & Chr(34) & Forms![Main Menu].Combo10 & Chr(34)
Else
Me.Filter = "[crop]=" & Chr(34) & Forms![Main Menu].Combo10 & Chr(34)
End If
Me.FilterOn = True
End If
End Sub
Note that Access tends to save filters with the report, especially when using layout view. You need to make sure the Report.Filter property is cleared when saving the report.
Use the same approach for the form.
I am trying to filter a subform with a combobox. What I have works, but it keeps bringing up an "Enter Parameter Value" textbox. When I enter the value I want to filter with, it searches the subform no problem. I would prefer to not have to enter the value though as it defeats the purpose of the combobox.
Here is my code for the ComboBox,
Private Sub ComboFE_AfterUpdate()
On Error GoTo Proc_Error
If IsNull(Me.ComboFE) Then
Me.SubFormPF.Form.Filter = ""
Me.SubFormPF.Form.FilterOn = False
Else
Me.SubFormPF.Form.Filter = "Lead_FE = " & Me.ComboFE
Me.SubFormPF.Form.FilterOn = True
End If
Proc_Exit:
Exit Sub
Proc_Error:
MsgBox "Error " & Err.Number & " in setting subform filter:" & vbCrLf & Err.Description
Resume Proc_Exit
End Sub
I have checked and made sure all the names are correct and match the corresponding items on my form.
Any Ideas?
Many Thanks
When applying a filter on a text column, the value needs quotes.
Me.SubFormPF.Form.Filter = "Lead_FE = '" & Me.ComboFE & "'"
To avoid problems if the value itself contains quotes, use Gustav's CSql() function from here: https://stackoverflow.com/a/36494189/3820271
Me.SubFormPF.Form.Filter = "Lead_FE = " & CSql(Me.ComboFE.Value)
This works for all data types.
Filters in Access seem to be 'sticky' - when you set one with VBA you can remove it but you can't set a different one.
I have a Access database for tracking student scores. It has tables subjects, teachers, students, tests and test_results. Each results record refers to a student and a test.
I have a form displaying tests with a subform displaying results. I want to search for tests using various criteria so I added some unbound fields to the (outer) form header and labelled them 'name', 'subject', 'start date', 'end date' and 'teacher'. I added a 'filter' button and a 'reset' button. Each search field is optional so any combination can be used: any left blank will be ignored.
This is the code for the filter button:
Me.Filter =
"([Forms]![testWithResults]![Text102] IS NULL OR test_name Like '*' & [Forms]![testWithResults]![Text102] & '*')
AND ([Forms]![testWithResults]![Combo89] IS NULL OR teacher = [Forms]![testWithResults]![Combo89])
AND ([Forms]![testWithResults]![Combo52] IS NULL OR subject = [Forms]![testWithResults]![Combo52])
AND ([Forms]![testWithResults]![Text83] IS NULL OR [Forms]![testWithResults]![Text85] IS NULL OR test_date BETWEEN [Forms]![testWithResults]![Text83] AND [Forms]![testWithResults]![Text85])"
Me.FilterOn = True
This is the code for the reset button:
Me.FilterOn = False
Me.Combo89 = Me.Combo89.DefaultValue
Me.Combo52 = Me.Combo52.DefaultValue
Me.Text83 = Me.Text83.DefaultValue
Me.Text85 = Me.Text85.DefaultValue
Me.Text102 = Me.Text102.DefaultValue
When I first load the form, the first time I search it all works perfectly. The filter button works just as expected and the reset button empties all fields and displays all records. But when I try to search again with new criteria I just get my old results again. To make it work I have to close and reopen the form.
When I replaced Me.Filter with DoCmd.ApplyFilter it still worked perfectly the first time but the second time I would get an error 'the expression is too complex to be evaluated'.
Since Access complains the Filter string is too complex, simplify it.
You want to base a Filter condition on a text box. At the time you create the Filter string, your code can check whether that text box is Null. If it is not Null, add a condition based on the text box's value. If it is Null, the Filter can simply ignore that text box.
Dim strFilter As String
With [Forms]![testWithResults]
If Not IsNull(![Text102]) Then
strFilter = strFilter & " AND test_name Like '*" & ![Text102] & "*'"
End If
If Not IsNull(![Combo89]) Then
strFilter = strFilter & " AND teacher = " & ![Combo89]
End If
If Not IsNull(![Combo52]) Then
strFilter = strFilter & " AND subject = " & ![Combo52]
End If
If Not (IsNull(![Text83]) Or IsNull(![Text85])) Then
strFilter = strFilter & " AND test_date BETWEEN " & Format(![Text83], "\#yyyy-m-d\#") _
& " AND " & Format(![Text85], "\#yyyy-m-d\#")
End If
End With
If Len(strFilter) > 0 Then
' use Mid() to discard leading " AND "
Debug.Print Mid(strFilter, 6) '<- view this in Immediate window; Ctrl+g will take you there
Me.Filter = Mid(strFilter, 6)
Me.FilterOn = True
Else
MsgBox "no conditions for Filter"
End If
In my front end DB I have a query "QryAcompanhamento" which has a calculated field "CalcAlerta" which has the following expression:
CalcAlerta: IIF((Date()>([Data_Vencimento]-5)) And is Null([Pag_Data-ProgPag]);"CrÃtico";IIF((Date()>([Data_Vencimento]-10)) And is null([Pag_Data-ProgPag]);"Urgente";""))
The calculated field works perfectly.
My front end also has a Continuous Form where I do some filtering stuff.
I've inserted a ComboBox in this form named boxAlerta and a button with the following code:
Private Sub Comando254_Click()
...
Dim boxAlerta as String
...
Alerta = "[CalcAlerta] = " & [boxAlerta] & ""
...
ElseIf Me.boxAlerta <> "" Then
Me.Filter = Alerta
Me.FilterOn = True
End If
When I click the button, it should filter the form showing only the values in the comboBox.
I also Have another of this code but that's not calculated field and works perfectly. i only get error when it's a calculated field.
Anyone know what I'm doing wrong?
Nevermind!
I used the following code and it works:
Alerta = "[CalcAlerta] = " & "'" & Me.boxAlerta & "'"
How it helps someone!
I need to let users filter a continuous form using values the user enters into a textbox. And the continuous form is also nested within a couple levels of navigation subforms. This sounds easy enough, but all the examples I find on the web use macros instead of vba.
I set up the structure and wrote an AfterUpdate procedure for a textbox txtFilter as follows:
Private Sub txtFilter_AfterUpdate()
Dim filterval As String
filterval = txtFilter.Value
With Forms!Main!NavigationSubform.Form!NavigationSubform.Form
.Filter = "LastName Like " & filterval
.FilterOn = True
End With
End Sub
I have played with different syntax, but none of it seems to work properly. Here is a link to download the relevant parts of the database from a file sharing site: http://jmp.sh/v/HGctZ4Ru74vDAjzN43Wq
Can anyone show me how to alter this so that users can use the textbox to filter the continuous form?
I got it to work using this: .Filter = "LastName Like """ & filterval & """"
Need those annoying String Identifiers even for strings sometimes.
Okay, To get the form to open with no records and then pull up just the records you (or the user) specifies is easiest with a bit of re-work.
(I'd recommend you working with a copy and not your original)
1:On your Continuous Form, remove the Recordsource; we're going to use Late Binding (Kinda)
2:Then delete the code under the txtFilter box, then delete the box itself.
3:Add a comboBox with something like this as the recordsource:
SELECT DISTINCT myTable.LastName FROM myTable ORDER BY myTable.LastName; (This will get you a unique list of last names so knowing how to spell the name will not be necessary, plus it assures at least one match)
4:In the After Update event of that combobox, add code like this:
Dim strSource As String
strSource = "SELECT mt.IntakeNumber, mt.ClientNumber, " & _
"mt.LastName, mt.FirstName, mt.ConsultationDate " & _
" FROM myTable mt " & _
"WHERE (mt.LastName)= '" & Me.cboFilter.Value & "'"
Me.RecordSource = strSource
Me.Requery
Obviously you'll need to change the table and field names as necessary, but hopefully you get the idea.
Option Compare Database
Option Explicit '<- always include this!!!!!
Private Sub txtFilter_AfterUpdate()
Dim strFilter As String
' only set Filter when text box contains something
' to search for ==> don't filter Null, empty string,
' or spaces
If Len(Trim(Me.txtFilter.Value & vbNullString)) > 0 Then
strFilter = "LastName Like '*" & _
Replace(Me.txtFilter.Value, "'", "''") & _
"*'"
' that Replace() prevents the procedure from breaking
' when the user enters a name with an apostrophe
' into the text box (O'Malley)
Debug.Print strFilter ' see what we built, Ctrl+g
Me.Filter = strFilter
Me.FilterOn = True
Else
' what should happen here?
' maybe just switch off the filter ...
Me.FilterOn = False
End If
End Sub