Refer to calculate field in VBA - ms-access

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!

Related

Parameter Value on Combo Box

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.

Access VBA: repeatedly change form filter with Me.Filter

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

access combobox values not showing

I am trying to create a form with 3 combo boxes on which will run a report from existing data. The combo boxes will filter down based on the data chosen in the next level up combo box.
However I'm having issues with the Batch Number Combobox not populating it's list
Now this is my VBA script:
Private Sub Form_Load()
Me.cboDate.RowSource = ""
Me.cboBatchNo.RowSource = ""
End Sub
Private Sub cboBottleNo_AfterUpdate()
Dim sDateSource As String
sDateSource = "SELECT [tblNewCC].[Date] FROM [tblNewCC]" & _
" WHERE [tblNewCC].[BottleNo] = " & Me.cboBottleNo.Value
Me.cboDate.RowSource = sDateSource
Me.cboDate.Requery
End Sub
Private Sub cboDate_AfterUpdate()
Dim sBatchSource As String
sBatchSource = "SELECT [tblBatchTotals].[BatchNo] FROM [tblBatchTotals] INNER JOIN [tblNewCC] ON [tblBatchTotals].[RunNo]=[tblNewCC].[RunNo]" & _
" WHERE [tblNewCC].[BottleNo] = " & Me.cboBottleNo.Value & _
" AND [tblNewCC].[Date] = " & Me.cboDate.Value
Me.cboBatchNo.RowSource = sBatchSource
Me.cboBatchNo.Requery
End Sub
From what I can see this is working alright on the vba side as I can see it replacing the rowsource of the batch number combobox, and in datasheet view it is giving me results.
However the combobox isn't showing anything in it's list....
Unless I go in make a change and save the sql query again.
Any clues?
The last part of sBatchSource should be " AND [tblNewCC].[Date] = #" & Me.cboDate.Value & "#" As an aside, 'Date' is a terrible name for a field. It is a reserved word in Access and will eventually cause you problems. Here is a helpful link http://www.fontstuff.com/access/acctut15pfv.htm

filter continuous form using textbox

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

Getting Records from Table in Access

I have this requirement where I have to check the data based on data given in other fields. I have table with 'N' fields. I should allow user to select 4 fields which are from the table. And then I should get all other fields of that particular record and display it to the user so that he can verify that the data he entered into table is correct. Please help.
Thanks
I have a clearer understanding now of what you require - hopefully this is what you need:
Assume you have a table called 'Phones'
The phones table has three primary fields: Manufacturer, Operating System, and Carrier
In addition to these primary fields there are secondary "spec" fields. For now we have three: ScreenSize, Frequencies, and Price.
I create a form with three combo boxes: ManufacturerFilter, OperatingSystemFilter, and CarrierFilter.
Each combo box's row source is similar to:
SELECT Carrier FROM Phones GROUP BY Carrier ORDER BY Carrier;
Where Carrier is replaced by Manufacturer and [Operating System] respectively.
I then add in all of the secondary fields, each bound to their own respective field.
You can also add in a button called "Retrieve" for now leave the click code blank.
At this point you have a few options. I'll highlight two, but both options will require the following procedure:
Private Function FilterStr() As String
Dim myFilterStr As String
' Include each filter if they are entered
If Nz(Me.ManufacturerFilter, "") <> "" Then myFilterStr = myFilterStr & "[Manufacturer]='" & Me.ManufacturerFilter.Value & "' AND"
If Nz(Me.OperatingSystemFilter, "") <> "" Then myFilterStr = myFilterStr & "[Operating System]='" & Me.OperatingSystemFilter.Value & "' AND"
If Nz(Me.CarrierFilter, "") <> "" Then myFilterStr = myFilterStr & "[Carrier]='" & Me.CarrierFilter.Value & "' AND"
' Remove the last AND statement
If myFilterStr <> "" Then myFilterStr = Mid(myFilterStr, 1, Len(myFilterStr) - 4)
FilterStr = myFilterStr
End Function
This function returns a filter string, based on the combo box options selected.
Option #1: Filter the Recordset
What we want to occur, is when a primary field value is selected, the records are filtered to display only those matching the criteria. Add the following code to the OnClick event of your Retrieve button:
Private Sub RetreiveButton_Click()
Dim myFilterStr As String
myFilterStr = FilterStr
If myFilterStr <> "" Then
Me.Filter = myFilterStr
Me.FilterOn = True
Else
Me.Filter = ""
Me.FilterOn = False
End If
End Sub
So what happens when the button is clicked, is that a filter string is created based on the values selected, and then a filter is applied to the form. If no values are selected in the combo boxes, the filter is cleared and turned off.
Option #2: Find a Record based on the Value
What we want is to select the values in the comboboxes, and then move to the record that matches the criteria.
Add the following code to the onClick event of the retrieve button.
Private Sub RetreiveButton_Click()
Dim rst As DAO.Recordset
Dim myFilterStr As String
myFilterStr = FilterStr()
If myFilterStr = "" Then
MsgBox "No Filter Selected", vbOKOnly, "Error"
Exit Sub
End If
Set rst = Me.RecordsetClone
rst.FindFirst myFilterStr
If rst.NoMatch Then
MsgBox "No Matching Records were found", vbOKOnly, "No Data"
Else
Me.Bookmark = rst.Bookmark
End If
Set rst = Nothing
End Sub
This uses the the same FilterStr() function to return a search string, but uses the recordset's FindFirst method to locate a record. If found, it will move to the record.
Hope that answers your question. As I indicated, the exact behaviour will vary but the underlying principle remains the same.