Subform opening with previous filter - ms-access

I've created a main form with a subform on it. The subform is filtered using a couple of combo boxes and command buttons on the main form.
For some strange reason when the form is closed and reopened, the subform is already showing as if it is filtered.
The method I'm using to filter the subform is to build an sql string that will be used as the subform's recordsource when a command button is pressed to apply the filter.
Here's the function that builds that sql string:
Public Function strSfaPaymentRecordSource() As String
strSfaPaymentRecordSource = "SELECT " _
& "[tblSfaRemittances].ID, [tblSfaRemittances].[SfaBudget], " _
& "[tblSfaRemittances].[PfrFundingLine], [tblSfaRemittances].[ContractNo], " _
& "[tblSfaRemittances].[LedgerDesc], [tblSfaRemittances].[TransDesc], " _
& "[tblSfaRemittances].[Period], [tblSfaRemittances].[Amount], [tblSfaRemittances].[Memo] " _
& "FROM tblSfaRemittances"
If Me.cboFundingLine > "" Or Me.cboReturnPeriod > "" Then
strSfaPaymentRecordSource = strSfaPaymentRecordSource & " WHERE"
End If
If Me.cboFundingLine > "" Then
strSfaPaymentRecordSource = strSfaPaymentRecordSource & " PfrFundingLine = '" & Me.cboFundingLine & "' And"
End If
If Me.cboReturnPeriod > "" Then
strSfaPaymentRecordSource = strSfaPaymentRecordSource & " Period = '" & Me.cboReturnPeriod & "'"
End If
If Right(strSfaPaymentRecordSource, 4) = " And" Then
strSfaPaymentRecordSource = Left(strSfaPaymentRecordSource, Len(strSfaPaymentRecordSource) - 4)
End If
End Function
And then the command button assigns the subform recordsource to the above string function:
Private Sub CmdApplyFilter_Click()
Me.frmSfaRemittances_sub.Form.RecordSource = strSfaPaymentRecordSource
End Sub
Now though, whenever I open the form, the subform is already filtered the same way (even if I filter it another way, close the form and come back to it).
I've checked the subform's recordsource and there is no WHERE clause saved there. I've also ran Debug.Print on the subform recordsource when the form and subform opens and still there is no WHERE clause being applied.
There's no code running on the any of the form or subform.form events, so I'm kind of at a loss as to why it's behaving this way. Any pointers would be appreciated :)

Related

MS Access - Creating a module that filter subform by different comboboxes using VBA

I have a form with "some" comboboxes and 1 subform that is currently filtered just by the combobox1 with the following VBA code:
Private Sub cmbType_AfterUpdate()
Dim strSQL As String
strSQL = "SELECT [qryStore].[Type], [qryStore].[Model], [qryStore].[SN], " _
& "[qryStore].[ID], [qryStore].[Position], " _
& "FROM qryStore " _
& "WHERE (((qryStore.Type)='" & Me.cmbType & "'));"
Me.subfrmStore.Form.RecordSource = strSQL
Me.subfrmStore.Form.Requery
End Sub
I want to turn this code in a module so i can Call the module once for all the comboboxes of the form instead of duplicate this code for each individual combobox..
How can i achieve that?!
Here:
Public Sub UpdateSubFormFromControl(ByRef ControlName as String)
Dim strSQL As String
strSQL = "SELECT [qryStore].[Type], [qryStore].[Model], [qryStore].[SN], " _
& "[qryStore].[ID], [qryStore].[Position], " _
& "FROM qryStore " _
& "WHERE (((qryStore.Type)='" & Forms!MyFormName.Controls(ControlName).Value & "'));"
End Sub
This allows you to pass the control name to a sub and do the same exact thing. However, you'll notice I had to fully qualify the form. I think its a better practice to always fully qualify (specifically for reasons such as yours).
I also left out the requery logic - either add it to this or leave it in the code that calls it.
Enjoy!

Problem to show graph in preview mode on in report

I have a form with a graphic and after modifying a certain field in the form, I change the number of graphic's records in this way:
Private Sub text_Cantidad_BeforeUpdate(Cancel As Integer)
Dim strsql As String
sql = "SELECT TOP " & CStr(text_Cantidad) & "Format([hora1],""hh:nn:ss"") AS Hora, TEMP_SET_POINT, TEMP_PAST_2 " & _
" , TEMP_PASTEURIZAD " & _
" FROM Qry_Registro WHERE Carpeta = '" & onodo.Parent.Text & "' AND Archivo = '" & Trim(onodo.Text) & _
"' ORDER BY Format([hora1],""hh:nn:ss""), Right(Format([hora1],""hh:nn:ss""),2);"
With Me.Gráfico1
.RowSourceType = "Table/Query"
.RowSource = sql
.Visible = True
.Object.Application.PlotBy = 2
End With
End Sub
Then with a button I want to print a report that has the same graph with the same properties and the same records. If I open the report in "report mode" everything is fine, but if I do it in "preview mode" I cannot change the recordsource property in any of the report or section's events.
The code I have for the button so far is:
Private Sub btn_Print_Click()
Dim strsql As String
TempVars.Add "SqlReport", ""
TempVars!SqlInformed = Me.Gráfico1.RowSource
'Error
DoCmd.OpenReport "Report", acViewPreview
'Ok
DoCmd.OpenReport "Informe1",acViewNormal
End Sub
The recordsource of a report can't be changed after the report is opened.
You shouldn't use dynamic sql to change the query of a form or report. If possible, use a WhereCondition parameter in the DoCmd.OpenForm or DoCmd.OpenReport statement. If your query Qry_Registro contains something like a unique ID, you can remove the dynamic "TOP" part from the report's query and replace it by a criterion for a WHERE clause using a subquery:
... WHERE ID IN (SELECT TOP x ID FROM ...
Placing all criteria in a variable, you can use that in the DoCmd.OpenReport statement.
strWhereClause = "ID IN (SELECT TOP " & CStr(text_Cantidad) & " ID FROM Qry_Registro " & _
"WHERE Carpeta = '" & onodo.Parent.Text & "' AND Archivo = '" & Trim(onodo.Text) & "' " & _
" ORDER BY Format([hora1], ""Long Time""))"
DoCmd.OpenReport ReportName:="MyReport", View:=acViewPreview, WhereCondition:=strWhereClause
Thanks a lot Wolfgang, but the issue is change the recordsource of chart in report. I solved placing in the properties of chart a query, then before open de report changed the propertie sql of querydef with the same sql that chart in form. Something like this
set querydef = currentdb.Querydefs("query_report_chart")
querydef.sql = "SELECT TOP " & CStr(text_Cantidad) & ....
DoCmd.OpenReport
Regards

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.

Open a form based on data from a recordset

I have an app that searches through customer information on a SQL Server database.
There are three forms:
The first allows the user to lookup info based on several different criteria, like Account no, Last name Phone Number, etc.
The second form correctly displays the information from the first form.
I want to open a third form based on a value in the result set on the second form, a field called Master_ID.
I have created a Global variable that stores the contents of the Master_ID field on the second form when the Master_ID field is clicked.
Then I want to execute the on click event on a button that contains the following code:
Private Sub tranHisBtn_Click()
Dim transferSQL As String
transferSQL = "SELECT dbo_Master_Accounts.Master_ID, dbo_Master_Accounts.FirstName, dbo_Master_Accounts.LastName, dbo_Transaction_Table.Date_of_Transaction, Format([dbo_Transaction_Table]![Time_of_Transaction],""hh:nn:ss ampm"") AS TranTime, dbo_Transaction_Table.Sku, dbo_Transaction_Table.Description, Right([dbo_Transaction_Table]![Description],6) AS tranAccnt, [dbo_Transaction_Table]![ArAmt]*-1 AS Amnt, dbo_Master_Accounts.Master_ID " & vbCrLf
transferSQL = transferSQL + "FROM dbo_Master_Accounts INNER JOIN dbo_Transaction_Table ON dbo_Master_Accounts.Master_ID = dbo_Transaction_Table.Account_Number " & vbCrLf
transferSQL = transferSQL + "WHERE (((dbo_Transaction_Table.Description) Like ""%Transfer To%"") AND ((dbo_Master_Accounts.Master_ID)=" & Chr$(34) & GBL_Master_Id & Chr$(34) & ")) " & vbCrLf
transferSQL = transferSQL + "ORDER BY dbo_Transaction_Table.Date_of_Transaction, Format([dbo_Transaction_Table]![Time_of_Transaction],""hh:nn:ss ampm"");"
Dim trancon As ADODB.Connection
Set trancon = CurrentProject.Connection
Dim tranRs As New ADODB.Recordset
tranRs.ActiveConnection = trancon
tranRs.CursorType = adOpenStatic
tranRs.Open transferSQL
'DoCmd.OpenForm "TransferbyNumFM" ', , , "Master_Id = 'transRs.fields(0)'"
MsgBox "good"
End Sub
I can't figure out how to set the record source for the third form. Everything runs perfectly until I try to open the third form.
As I said: Open the form with DoCmd and set the recordsource of the Form object in the OnOpen Event of the 3rd form to the SQL string you have. No need to create a recordset, either. And never try to pass a recordsource as a filter in a DoCmd.OpenForm
Oh, and my error: since you have a global variable (i.e. a public variable declared in a module) you don't even need to pass it as an OpenArgs, you can simply do the following on Button Click
DoCmd.OpenForm "TransferbyNumFm"
and then, in the class module of Form3 do
Option Compare Database
Option Explicit
Private Sub Form_Open(Cancel As Integer)
Dim transferSQL As String
transferSQL = _
"SELECT dbo_Master_Accounts.Master_ID, " & _
"dbo_Master_Accounts.FirstName, " & _
"dbo_Master_Accounts.LastName, " & _
"dbo_Transaction_Table.Date_of_Transaction, " & _
"Format([dbo_Transaction_Table]![Time_of_Transaction],'hh:nn:ss ampm') AS TranTime, " & _
"dbo_Transaction_Table.Sku, dbo_Transaction_Table.Description, " & _
"Right([dbo_Transaction_Table]![Description],6) AS tranAccnt, " & _
"[dbo_Transaction_Table]![ArAmt]*-1 AS Amnt " & _
"FROM dbo_Master_Accounts " & _
"INNER JOIN dbo_Transaction_Table ON dbo_Master_Accounts.Master_ID = dbo_Transaction_Table.Account_Number " & _
"WHERE(((dbo_Transaction_Table.Sku) Like '%Transfer%')) " & _
"ORDER BY dbo_Transaction_Table.Date_of_Transaction"
Me.RecordSource = transferSQL
End Sub
The Recordsource of Form3 can be unassigned before this point, though you will need it to add fields (but you can remove it later on)

VBA code to create a report in MS Access

Can anyone help me create a code satatement that will allow me to create a report with the sQ statement below? The problem I'm having is that my form allows you to input a Cost center, but when I click on the command button to execute the code it asks me to input the cost center again before it shows me the report. I want to eliminate having to enter the cost center again and just take it from when it is enters on the form.
Private Sub CmdCC_Click()
Set mydb = CurrentDb
myCC = txtCC.Value
If IsNull(myCC) Or myCC = "" Then
MsgBox "Please enter a Cost Center!", vbCritical + vbOKOnly, pTitle
End If
sQ = "SELECT ZBASED.ACCT_UNIT, CenterName, ZBASED.ACCOUNT, ZBASED.ACCOUNT_DESC " & _
"FROM ZBASED, CCtable " & _
"WHERE (ZBASED.ACCT_UNIT = " & myCC & ") And (CenterNo = " & myCC & ") " & _
"ORDER BY ZBASED.ACCOUNT;"
If the report is already based on say,
SELECT ZBASED.ACCT_UNIT, CenterName,
ZBASED.ACCOUNT, ZBASED.ACCOUNT_DESC
FROM ZBASED, CCtable
(There is no point in using ORDER BY with a report, you must use the report's own Oder & Grouping properties)
You can use the Where argument of OpenReport:
DoCmd.OpenReport "ReportName", acViewPreview, , "ZBASED.ACCT_UNIT = " & myCC _
& " And CenterNo = " & myCC
All you have to do is reference the form you are calling the report from in the SQL, for example
SELECT foo FROM bar WHERE foo=[Forms]![frmReporting]![txtFoo]
You then have a button on frmFoo that opens the report, you can include some logic in before the docmd.OpenReport call to validate the input i.e. make sure they have entered a cost centre