Access VBA Multiple Sorting Criteria - ms-access

The Case: I have a form that has several fields of entry. A button contained within this form runs a query and generates a report based on the form entry fields.
I have created 3 comboboxes that will allow the user to sort the report on various criteria (ie. sort by Analyst name, then by Meeting Date, then by Ticker).
Combo Box 1 = Sort_By;
Combo Box 2 = Sort_By_2;
Combo Box 3 = Sort_By_3
The Code:
Private Sub Run_Query_Button_Click()
If Revisit_Check.Value = False Then
DoCmd.OpenQuery "Important Information Extracted"
DoCmd.Close
DoCmd.OpenReport "Important Information Extracted", acViewReport
DoCmd.SetOrderBy Sort_By Sort_By_2 Sort_By_3
Else
DoCmd.OpenQuery "Revisit"
DoCmd.Close
DoCmd.OpenReport "Revisit_Report", acViewReport
DoCmd.SetOrderBy Sort_By Sort_By_2 Sort_By_3
End If
End Sub
This code returns a syntax error. It does not sort on the three "sort by" criteria. If I use only on of the criteria in the following fashion:
Private Sub Run_Query_Button_Click()
If Revisit_Check.Value = False Then
DoCmd.OpenQuery "Important Information Extracted"
DoCmd.Close
DoCmd.OpenReport "Important Information Extracted", acViewReport
DoCmd.SetOrderBy Sort_By
The code runs properly and sorts on the given "sort by" value. If instead of using the form field comboboxes to sort, I use the actual field names, for instance:
Private Sub Run_Query_Button_Click()
If Revisit_Check.Value = False Then
DoCmd.OpenQuery "Important Information Extracted"
DoCmd.Close
DoCmd.OpenReport "Important Information Extracted", acViewReport
DoCmd.SetOrderBy "Analyst, Meeting Date, Ticker"
...
Everything works fine as well. Why, when I use the three sort criteria, do I get a syntax error? How can I sort on these three criteria?

Assuming Sort_By is the values you get in the comboboxes you are seeking you will need something more like this:
Private Sub Run_Query_Button_Click()
If Revisit_Check.Value = False Then
DoCmd.OpenQuery "Important Information Extracted"
DoCmd.Close
DoCmd.OpenReport "Important Information Extracted", acViewReport
DoCmd.SetOrderBy Sort_By & ", " & Sort_By_2 & ", " & Sort_By_3
Else
DoCmd.OpenQuery "Revisit"
DoCmd.Close
DoCmd.OpenReport "Revisit_Report", acViewReport
DoCmd.SetOrderBy Sort_By & ", " & Sort_By_2 & ", " & Sort_By_3
End If
End Sub
Notice the & ", " & to make it into the same kind of string as "Analyst, Meeting Date, Ticker" which you said had worked. Otherwise your sort you are sending in the first time would look like this: "AnalystMeeting DateTicker"

Related

Error On click Button Docmd Report Error 3464

Hi Everyone How Are You I hope You Are Well.
I Am Working On A MS Access Application And Want Fetch Result From List Box With On Click Button
But I'm Facing A Error Data Type Mismatch In Criteria expression
Here is My Code On Click Button
Private Sub ViewBalance_Click()
'Dim listrpt As String
If IsNull(listrpt) Then
MsgBox "Please Select The Account Name", vbOKOnly, "Warning"
Exit Sub
End If
DoCmd.OpenReport "List All Parties Balance", acViewPreview, , "[Account ID] = """ & listrpt &
""""
Me.FilterOn = True
End Sub
And Here is My On Report Load Filter But This Filter Working Fine Above Code Give me Error
Report Load Code
Private Sub Report_Load()
DoCmd.Maximize
If MsgBox("Do You Want To Filter Available Balance Only?", vbYesNo + vbQuestion) = vbYes Then
Dim strFilter As String
strFilter = "[RQ]>0"
'verify that it looks good
Me.Filter = strFilter
Me.FilterOn = True
End If
End Sub
Report Name: List All Parties Balance
Query Name Where is Field Name: Account ID is: ListBalance
And listrpt Response Account ID = 60023
Please Anyone Give me A Support & Help Thanks in Advance

Ms Access filter reports in runtime mode

Does anyone knows how to filter reports the right way within Access runtime mode?
The usual code with DoCmd doesn't work.
This is what I tried for the report:
Private Sub Befehl217_Click()
DoCmd.OpenReport "Tagesbericht", acViewPreview
End Sub
Private Sub Bezeichnungsfeld26_Click()
DoCmd.GoToControl "DateFilter"
DoCmd.RunCommand acCmdFilterMenu
End Sub
This didn't work. Access complained that "FilterMenu isn't available".
I tried to create a context menu but this only displayed me cut, copy and paste.
You confirmed your report includes a control named Bezeichnungsfeld26 and when the user clicks in that control, you want to bring up the filter menu for that control.
When the user clicks in that control, it has the focus, so there is no need for GoToControl. And you don't want to go to a different control if you want the user to filter on Bezeichnungsfeld26.
Disable the GoToControl line ...
Private Sub Bezeichnungsfeld26_Click()
'DoCmd.GoToControl "DateFilter"
DoCmd.RunCommand acCmdFilterMenu
End Sub
You can use the Filter property:
Me.Filter = "[YourField] = " & somevalue & ""
Me.FilterOn = True
or, to expand on your current method:
DoCmd.OpenReport "Tagesbericht", acViewPreview, , "[YourField] = " & somevalue & ""
If you filter for a date you must pass a properly formatted string expression for the date:
Dim FilterDate As Date
FilterDate = Date
DoCmd.OpenReport "Tagesbericht", acViewPreview, , "[DateFilter] = #" & Format(FilterDate, "yyyy\/mm\/dd") & "#"

Access report - Recordsetclone as. Recordsource

I have a form, which has button for report. I want to set Report .Recordsource to whatever on screen is, so basically I need .RecordsetClone of form send to Report. Here is what I tried, but It doesn't work:
Me.Recordsource= Forms!Myform.RecordsetClone
I get an invalid argument on that. Any ideas how to solve this ?
EDIT:
I tried this too - this button is placed on form which has records and opens Report :
Private Sub cmdOpenReport_Click()
DoCmd.OpenReport "MyReport", acViewReport
Reports![MyReport].RecordSource = Me.RecordSource
Reports![MyReport].Filter = Me.Filter
Reports![MyReport].FilterOn = True
End Sub
You can't do that, but you may get away with:
Me.RecordSource = Forms!Myform.RecordSource
though that will not include a filter applied to the form. However, the Filter can be copied the same way, and then:
Me.Filter = Forms!Myform.Filter
Me.FilterOn = True
while sorting must be specified in the report the usual way.
Proof of concept
Private Sub Report_Open(Cancel As Integer)
If MsgBox("Mod 2?", vbQuestion + vbYesNo, "Select") = vbYes Then
Me.RecordSource = "Select * From TestTable Where Id Mod 2 = 0"
End If
End Sub
Gustav, this is correct answer. I have opened another thread for that, but I wasn't aware of what is wrong and where. Sorry for crossposting. here is link to my thread:
Access Report - show current recordsource of another form
Dim strWhere As String
Me.Dirty = False
With Me.Recordset.Clone
Do Until .EOF
strWhere = strWhere & "," & !ID
.MoveNext
Loop
End With
strWhere = Mid(strWhere, 2)
DoCmd.OpenReport "MyReport", acViewReport, WhereCondition:="ID In (" & strWhere & ")
Moderators can delete one of the threads, I can't do that.

Setting a value of a field in my table for future use

I have an access Db which was originally written ib Access 2003 but has since been upgraded to Access 2007 - the problem I am experiencing is as follows:
I have a table "tblBookings" which stores all relevant data for a particular clienst booking or quote, the client field of this table is linked to the PK of the CLient Table (tblClients) when a quote is accepted the user opens the main form, selects the client and in a dropdown selects the booking number then proceeds to "Edit booking" where the user can either edit the booking or confirm it. when the user clicks "confirm Booking" cmdButton the open form closes and the "Create Invoice" form opens. From a dropdown list the user selects the booking number and then prints the Pro-Forma Invoice or invoice. the print pro-forma cammand button opens a report that prints the necessary document, when the Print Invoice command is clicked then the print invoice form is opend where the user has the option to record any ayments made against the invoice.
This being said it is essential to first print a pro-forma before printing an invoice so i need to set a yes no field in the table to yes or true if a pro forma has been printed in which case the invoice button will become visible and remain hidden if one has not been printed yet.
the event procedure on cmdProForma is below (this is where I need ti set the yes/no field in the Pro field which is tblBookings and set to a yes/no field.
Private Sub CmdProForma_Click()
Dim rs As New ADODB.Recordset 'recordset of existing refs
Dim t As String 'temp string var
Dim stDocName As String
Dim stLinkCriteria As String
Dim i As Integer 'temp ref variable
i = CInt(Right(txtBRef, 5))
t = [txtBRef]
With rs
.Open "SELECT BRef,Conf,lock,Pro FROM tblBookings WHERE Bref=" & t & ";", CurrentProject.Connection, adOpenDynamic
If .BOF Or .EOF Then 'no such ref
MsgBox "No booking with ref '" & fRef(CInt(t), "B") & "' exists.", vbExclamation, "No booking"
Else 'ref found: open invoice
strSQL = "UPDATE tblBookings SET Pro = True"
'db.Execute strSQL, dbFailOnError
DoCmd.Close acForm, "frmBRefEnter"
' !Form!frmBRefEnter!Pro = True
DoCmd.OpenReport "rptInvoice1", acViewPreview, , "BRef=" & t
DoCmd.OutputTo acOutputReport, "rptInvoice1", acFormatPDF, destDIR & "\Inv\" & fRef(i, "Pro-Forma") & ".pdf"
End If
End With
End Sub
Add the checkbox for proforma printed to the form. It will be a good guide for your users as to why they cannot print an invoice. You can set the properties to Locked=True
Private Sub CmdProForma_Click()
''"From a dropdown list the user selects the booking number",
''so the booking number must exist, no need to check
DoCmd.OpenReport "rptInvoice1", acViewPreview, , "BRef=" & Me.txtBref
DoCmd.OutputTo acOutputReport, "rptInvoice1", _
acFormatPDF, destDIR & "\Inv\" & fRef(i, "Pro-Forma") & ".pdf"
Me.Pro = True ''Checkbox
DoCmd.Close acForm, "frmBRefEnter"
End Sub
For the invoice button:
Me.cmdInvoicePrint.Visible = Me.Pro
If Me.Pro is ticked, Me.Pro will be true and the invoice button will be visible.

Search form in Access

I want to implement a search form to operate on a table on access.
But when I choose the table then create a From, I get all the table data in the form instead of search field. And when I change any value, the table values change. I want to have a text field where user can enter search criteria and hit a search btn and the search result appears as a table in the form or as a message box.
You could add the data to the form after the search, but to keep things tidy, you might like to consider an unbound form with search box(es) and a subform for results. Let us say you have two boxes, txtName and txtDate and a search button, then a very rough idea would run:
strSQL = "SELECT aName, aDate FROM aTable WHERE 1=1 "
If Not IsNull(txtName) Then
strWHERE = " AND aName Like '*" & Replace(txtName,"'","''") & "*'"
End If
If Not IsNull(txtDate) Then
strWHERE = strWhere " AND aDate =#" & Format(txtdate,"yyyy/mm/dd") & "#"
End If
Me.SubformControlName.Form.RecordSource = strSQL & strWhere
You should, of course, make sure that the data in the controls in sensible and clean and that records are returned.
You can use something like this to put your form in Search mode when opened:
Private Sub Form_Open(Cancel As Integer)
'DoCmd.DoMenuItem acFormBar, acRecordsMenu, acFilterByForm, , acMenuVer70
DoCmd.RunCommand acCmdFilterByForm
End Sub
I have a search form created that I use that is very handy. In order to setup a form to search you need to create a search query. For example my form has the fields: Keywords and Source. So you need to link the query to the table that houses the data. The search query I have is
SELECT KWTable.KW AS Expr1, KWTable.Code, KWTable.Source
FROM KWTable
WHERE (((KWTable.KW) Like "*" & [Forms]![Search_Form]![KW_Text] & "*") AND ((KWTable.Source) Like "*" & [Forms]![Search_Form]![Source_Text] & "*"));
I type the words into the boxes and click a button to execute. The button code looks like
Private Sub Command8_Click()
On Error GoTo Err_Command8_Click
Dim stDocName As String
stDocName = "Search_Query"
DoCmd.OpenQuery stDocName, acNormal, acEdit
Exit_Command8_Click:
Exit Sub
Err_Command8_Click:
MsgBox Err.Description
Resume Exit_Command8_Click
End Sub
I hope this helps.