Access msgbox Yes No to Choose Report - Opening Wrong Report? - ms-access

I set up the following simple code, to choose if the report should show "excluded" groups or not.
Private Sub cmdRptWorktypesByGroups_Click()
Dim rptExclYN As String
rptExclYN = MsgBox("Would you like this report with excluded groups (Yes)" & vbclrf & " or without excluded practice groups (No)?", vbYesNo, "Choose Report With or Without excluded groups")
If rptExclYN = Yes Then
DoCmd.OpenReport "rptWorkTypebyGroups", acViewReport
Else
DoCmd.OpenReport "rptWorkTypebyGroupsNoExcl", acViewReport
End If
End Sub
That is my code. It should be totally straight forward. Problem is, that when the user clicks Yes, it opens the rptWorkTypebyGroupsNoExcl report. When I click No, it still opens that same report. Can anyone tell what I might be doing wrong?
I originally had the rptWorkTypebyGroups report, with a query record source. I copied that report, renamed the copy as rptWorkTypebyGroupsNoExcl, and saved it's Record Source query as it's own name. I can't tell why the message box isn't opening the right report. Can anyone please help?
Thank!

The MsgBox() function returns a VbMsgBoxResult value (an Integer), not a string.
Since you apparently don't have Option Explicit on, Yes is created as new empty Variant, so your If condition will always be false, no matter what you selected.
Put Option Explicit at the top of each module.
It enforces variable declaration and reports undeclared or misspelled variables/constants at compile time.
To have this automatically in new modules, set the Require Variable Declaration option in the VBA Editor.
Correct code:
Private Sub cmdRptWorktypesByGroups_Click()
Dim rptExclYN As VbMsgBoxResult
rptExclYN = MsgBox("Would you like this report with excluded groups (Yes)" & vbCrLf & " or without excluded practice groups (No)?", vbYesNo, "Choose Report With or Without excluded groups")
If rptExclYN = vbYes Then
DoCmd.OpenReport "rptWorkTypebyGroups", acViewReport
Else
DoCmd.OpenReport "rptWorkTypebyGroupsNoExcl", acViewReport
End If
End Sub
Edit: It's vbCrLf, not vbclrf.
Another one that Option Explicit would have caught.

I'm a moron. I was having it say if rptExclYN = Yes and not rptExclYN = vbYes. My bad. Here's the simple code that works:
Dim rptExclYN As Variant
rptExclYN = MsgBox("Would you like this report with excluded groups (Yes)" & vbCrLf & _
" or without excluded groups (No)?", vbYesNo, "Choose Report With or Without Excluded Groups")
If rptExclYN = vbYes Then
DoCmd.OpenReport "rptWorkTypebyGroups", acViewReport
ElseIf rptExclYN = vbNo Then
DoCmd.OpenReport "rptWorkTypebyGroupsNoExcl", acViewReport
End If
Hope this helps someone else, because then it would mean I'm not the only one missing simple things.

Related

Using subform for report options

Pretty new at this. I have a main form with a list box of job numbers and a subform for the different reports. I want to be able to select a job name and then double click the report name to preview it but it gives me an error. It doesn't seem to recognize my selected job name from the list box. Error message is "Compile Error: Method or Data Member Not Found". See image.
Here is the code i'm using which is on the Double Click event on the text box in the subform.
Private Sub ReportName_DblClick(Cancel As Integer)
Dim strFilter As String
If IsNull(Me.lstJobName) Then
MsgBox "You Must Select A Job"
Me.lstJobName.SetFocus
Exit Sub
End If
strFilter = "JobName = '" & Me.lstJobName & "'"
DoCmd.OpenReport ReportName.Value, acViewPreview, , strFilter
End Sub
Trying to figure this out step by step so just need the report to preview for now. Later I will want to check off the reports that I need printed then just click a button to print.
The code is behind the subform therefore the Me. qualifier is alias for the subform and code is looking for the listbox on the subform but it is actually on the main form.
strFilter = "JobName = '" & Me.Parent.lstJobName & "'"

Access Print Report Options for Custom Form Printing

I have a custom form and report in Access and I have a 'Print Report' button on my form that takes the current record for the database and prints out the Report I created for it. My problem is the code I have does a quick print on the Report. Once I press the "Print report" button I created, it pops up the Print Preview but then automatically prints the report. I want to be able to look at the preview before the report prints, open the print dialog and be able to select which printer I want to use, instead of it going to Quick Print and using the default printer. My code is below for the current format, I'm not sure where or how to make this adjustment. Thanks in advance for any assistance!
Private Sub cmdPrintReport_Click()
Dim strReportName As String
Dim strCriteria As String
strReportName = "rptDrillReclamation"
strCriteria = "[HoleNumber]='" & Me![HoleNumber] & "'"
DoCmd.OpenReport strReportName, acViewPreview, , strCriteria
On Error GoTo Err_cmdPrintReport_Click
Dim stDocName As String
stDocName = "rptDrillReclamation"
DoCmd.OpenReport stDocName, acNormal
Exit_cmdPrintReport_Click:
Exit Sub
Err_cmdPrintReport_Click:
MsgBox Err.Description
Resume Exit_cmdPrintReport_Click
End Sub
You are opening the report twice! Two lines of code starting with DoCmd.OpenReport.
The first time the View parameter is set to acViewPreview so it shows up (=previews) on the screen without printing. The second time the View parameter is set to acNormal (= no preview) so it prints directly to the printer without showing on the screen.
BTW The second time you are printing all the records because the criteria are not sent!
Remove the second Docmd.OpenReport.... It is unnecessary and is what is causing your problem.

Wrong RecordCount on Filtered Form with SQL View DataSource

I am using an Access2010 project as frontend, referring to a MS SQL Server 2008 as backend. Within my Access project there is form frmKlientenÜbersicht. This form has a view abfKlientenÜbersicht as dataSource.
Now I am trying to get the current number of records showing up in my form by using this code:
Private Sub Form_Current()
Debug.Print "Form_Current: " & anzahlDatensätze
lblAnzahlDatensätze.Caption = anzahlDatensätze & " Klient(en)"
End Sub
Private Function anzahlDatensätze() As Integer
Dim rs As Recordset
Set rs = Me.RecordsetClone
rs.MoveLast
anzahlDatensätze = rs.RecordCount
End Function
This works fine until I am using some filters. If I am using any filter on my form, the number of records stays unchanged!
What do I have to change to get the current number of records showing up (if filtered or not)?
What is the reason why my code does not show the correct number of records?
EDIT: According to the given comments and answers I tried setting Count([pkKlient] onto a textbox (see new pic) and tried DCount("*", "abfKlientenÜbersicht", me.Filter) from within VBA Code.
Unfortunatelly it seems that the filterClause is not valid when using it as parameter value for DCount. (see pic for filterClause).
As you can see count(..) does not result in a correct number - and the filterClause (generated by access!!) seems not to be valid for use by DCount(..)
If someone wants to try it, on your own, just create an ADP, add a form, add a view, form dataSource is a view, set a filter, and try to get the number of records?!!
Looking forward for any comments/answers/hints!
with VBA, DCount will give you what you need
DCount("*", "MyTable", Me.Filter)
If you want to put this on the form, there's an easier way. use an unbound box, and set it to =count([FieldName])
This count should remain correct, regardless of if it's counted filtered records or not.
Some notes, there are a dozen things that could go wrong with this, it could hardly even be called tested. However, it was returning the correct count for me.
Apparently, the form filter just hides records, whereas this will apply a real filter. However, you need to get the format into the right shape for a valid filter. In the end, a WHERE statement would probably be easier.
Private Sub Form_ApplyFilter(Cancel As Integer, ApplyType As Integer)
With Me.Recordset
''Filter
If ApplyType = 1 Then
''Very, very roughly. Remove form name, use single quotes
''You will need a lot more code for safety
sfilter = Replace(Me.Filter, "[" & Me.Name & "].", "")
sfilter = Replace(sfilter, """", "'")
.Filter = sfilter
MsgBox "Recordset : " & Me.Recordset.RecordCount & vbCrLf _
& "Filtered : " & .RecordCount
Else
''Remove filter - ApplyType 0
.Filter = ""
End If
End With
End Sub
Additional note with similar caveats
You can also set a textbox to something on these lines:
=IIf([FilterOn]=True,DCount("id","ATable",
Replace(Replace([Filter],"[" & [Name] & "].",""),"""","'")),Count([id]))
(Remove the break in the line, it is cosmetic)

Is it possible to click on a report record to open relevant form in Access using VBA

I have a report with details of jobs/tasks, and also a form which contributes the majority of the data towards that report. Given that a report is a nice way of looking at the larger picture of the data, and a form is the best way of editing data, I would like to be able to click on a row, and have it open up the relevant record in the form view.
Does anyone know how to do this through VBA? In my mind it should be possible, though my knowledge of objects in Access is limited.
Update
I've implemented the following code for my report:
Private Sub Edit_Click()
Dim EntityName As String
Dim DocName As String
DocName = "Entity: Overview"
strWhere = "[Entity Name]='" & Entity & "'"
DoCmd.OpenForm DocName, acNormal, , EntityName
End Sub
It successfully opens the correct form, and it also grabs the correct entity name, however it isn't filtering properly. I can't see what the issue is with the code.
In your Edit_Click() procedure, you have EntityName as the WhereCondition parameter to OpenForm.
DoCmd.OpenForm DocName, acNormal, , EntityName
However, you haven't assigned anything to EntityName, so it's an empty string. I think you should use strWhere as the WhereCondition.
Private Sub Edit_Click()
Dim strWhere As String
Dim DocName As String
DocName = "Entity: Overview"
strWhere = "[Entity Name]='" & Me.Entity & "'"
DoCmd.OpenForm DocName, acNormal, , strWhere
End Sub
I assumed Entity is the name of a control, and that's where you get a value to build strWhere. If there is no control in the report by the name of Entity, then the code won't work even if there is an Entity in the original query.
You should be able to add an On Click event in the Detail section of the report, then add something like this in the VBA handler:
DoCmd.OpenForm "MyForm", acNormal, "", "ID=" & ID.Text
(where MyForm is the target form, and ID is a hidden or visible control in your report that identifies the current record).
You say report, but you should not be using a report but a continuous form or datasheet. You can then add events to any of the controls on any line, and add a double-click event, if you do not want to drive your users insane. You could also add a command button if that would be clearer to your users, or format the "link" textbox to underline. The record opened by the action shown by #dbaseman will open which even record has the focus (current record). And that will lead you to discover what you can and can't do with a continuous form :D

Multi-Page vs Multi-PDF Loop problems

I have a form that contains multiple partners that share a "pool". The partners are listed on a subform. After I'm done entering the information, I want a button to run a report for each of the partners with their specific information. But since it's multiple partners and I need one report for each (which I then want to email), I want to use a Loop to go through each of the partners.
EDIT1: Added entire code for review. I do have Option Explicit in and I have compiled it as well.
Private Sub btn_Run_Click()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strSQL As String
strSQL = "Select * FROM Cobind_qryReport WHERE PartPoolName = """ & Me.TopLvlPoolName & """"
Debug.Print "strSQL: " & strSQL
Set db = CurrentDb
Set rs = db.OpenRecordset(strSQL)
On Error GoTo Err_PO_Click
If MsgBox("Do you wish to issue the cobind invites?", vbYesNo + vbQuestion, "Confirmation Required") = vbYes Then
rs.MoveFirst
Do While rs.EOF = False
DoCmd.OutputTo acOutputReport, "Cobind_rptMain", acFormatPDF,_
"K:\OB MS Admin\Postage\CoBind Opportunities\Sent Invites\" _
& rs!CatCode & "_" & rs!PartPoolName "Cobind Invite_" & _
Format(Now(), "mmddyy") & ".pdf"
DoCmd.SendObject acSendReport, "Cobind_rptMain", acFormatPDF, ,_
, , " Cobind Invite", "Please find the cobind invite attached._
Response is needed by " & [RSVP] & ". Thank you.", True
rs.MoveNext
Loop
End If
Exit_PO_Click:
MsgBox ("It didn't work")
rs.Close
Set rs = Nothing
Set db = Nothing
Exit Sub
Err_PO_Click:
MsgBox Err.Description
Resume Exit_PO_Click
End Sub
This should allow me to create a report for each record in my query, save it to my server, then open an email to send it out. Right now, it appears that the [PartPoolName] is hanging up the code because I'm getting a "Microsoft Office Access can't find the field "|" referred to in your expression." If I take out the [PartPoolName], it'll create a PDF with four pages (each page showing a partner), where I want to end up with four separate PDFs.
The first thing you should do is add Option Explicit to the Declarations section of your module.
Then, from the Visual Basic editor's main menu, select Debug->Compile [your project name here]
Fix all the problems the compiler complains about. I suspect one of the compiler's first complaints may be triggered by this section of your code:
rs.MoveFirst
Do While Recordset.EOF = False
Do you have two recordset objects open, or one?
After you fix everything the compiler complains about, try your revised code.
If you get runtime errors, show us the exact error message and which code line is highlighted.
If the part of your code you haven't shown us includes an error hander, you can disable that error handler like so:
'On Error GoTo Err_PO_Click
Error handlers are great for production to shield users from errors. However, during development you really need to be able to identify which code line causes the error.
Alternatively, you can leave your error handler active and select Tools->Options from the editor's main menu. In the Options dialog, select the General tab, then select the "Break on All Errors" radio button and click OK. You can switch that option back to "Break on Unhandled Errors" after you finish your testing.
Update: You wrote: Right now, it appears that the [PartPoolName] is hanging up the code because I'm getting a "Microsoft Office Access can't find the field "|" referred to in your expression."
What is [PartPoolName]? If it's a field in the recordset, you can reference its value as rs!PartPoolName If it's something else, perhaps a global variable, give us more information about it.
Update2: Whenever your current code completes without error, you will hit this:
Exit_PO_Click:
MsgBox ("It didn't work")
Can that be right?
Update3: This OutputTo statement is your issue now, right?
DoCmd.OutputTo acOutputReport, "Cobind_rptMain", acFormatPDF,_
"K:\OB MS Admin\Postage\CoBind Opportunities\Sent Invites\" & _
"Cobind Invite_" & Format(Now(), "mmddyy") & ".pdf"
Cobind_rptMain is a report. It has a RowSource for its data. You're calling OutputTo with that report 4 times (once for each of the 4 rows in the recordset). Yet you expect 4 different versions of that report ... a separate report for each PartPoolName value?
To finish off the fine work by HansUp visit a page on how to print a report for a single record and how to generate reports to attach to emails. See the Emailing reports as attachments from Microsoft Access page.