Access report, populate label with results of query - ms-access

I have, what I think, is a pretty basic Access file, with a report. The report is based off a query. The query is:
SELECT * FROM dbo_NewPatient WHERE id=[Patient to view];
This works good, and prompts me for an id, I enter Id, and the results are the patient I want to see. Now I want to build a report that is based on this query, but I want to create a label on the report, that populates data from the results, so I've got this code:
Private Sub Report_Open(Cancel As Integer)
Label2.Caption = "Patient Name is " & PatientName & " his time in hospital is ... "
End Sub
I want that "PatientName" variable to be the data returned from the query. I've tried PatientName.Value, and PatientName.Text, but each time, i get an error message:
'The expression you entered has a field, control, or property name that Microsoft Office Access can't find'.
I'm assuming it doesn't know what "PatientName" is, perhaps because when I double click to open the report, I'm not yet prompted for the [Patient to view] variable, so the code doesn't yet know what PatientName is. How can I correct this, or is there a better way to go about this?
Thanks!

2 answers.
First, in your code:
Label2.Caption = "Patient Name is " & PatientName & " his time in hospital is ... "
Move it to the Private Sub Report_Load() procedure. Access will then know the value of PatientName.
Or, you can assign it in the report designer. However, you can't do this with labels, but you can with textboxes. Just lock the textbox control and it act just like a label. Put it in the Control Source property, preface it with an =, and put brackets around the fieldname. So...
="Patient Name is " & [PatientName] & " his time in hospital is ... "

It sounds like rather than doing this in VBA code, you just want to bind a column from your query (PatientName) to a label in your report. Don't do that in VBA code, do that in the report designer.

Your code could be tweaked to use Me to access the patient name field
Private Sub Report_Open(Cancel As Integer)
Label2.Caption = "Patient Name is " & Me!PatientName & " his time in hospital is ... "
End Sub
Edit:
It was pointed out that you can't do this on the open event. There is another event that you can hit that will work if you have more than one record to work with. You can use that group header paint event like this. (I even tested it...)
Private Sub GroupHeader0_Paint()
Label2.Caption = "Patient Name is " & Me!PatientName & " his time in hospital is ... "
End Sub

Related

MS Access Tab Control Name with Number of Records

I am developing an Access database (using Office 2016) and have several tab controls which I want to display the number of records in the subform/subreport.
After a lot of searching etc I have it working for the subforms using a function which I call in the main forms current event (but in a seperate function so I can also call via a macro when I change the main forms record with a combo box, as it wasn't updating otherwise). The code I am using is:
Function ClientTotals()
Dim i As Integer
i = Form_sbfrm_ClientContacts.Recordset.RecordCount
Form_frm_Clients.ClientTabs.Pages("Contacts").Caption = "Contacts (" & i & ")"
End Function
This works perfectly for me and my tab name becomes "Contacts (No. of records)" but I can't get the syntax right to change this to work for a report, is it possible?
I have tried:
Function ClientTotals()
Dim i As Integer
i = Form_sbfrm_ClientContacts.Recordset.RecordCount
Form_frm_Clients.ClientTabs.Pages("Contacts").Caption = "Contacts (" & i & ")"
Dim j As Integer
j = Report_rpt_CurrentProjects.Recordset.RecordCount ' this line is highlighted with the debugger
Form_frm_Clients.ClientTabs.Pages("Current Projects").Caption = "Current Projects (" & j & ")"
End Function
As well as:
Dim j As Integer
j = rpt_CurrentProjects.Report.Recordset.RecordCount ' this line is highlighted with the debugger
Form_frm_Clients.ClientTabs.Pages("Current Projects").Caption = "Current Projects (" & j & ")"
and various others.
Another question I have is why is the syntax for the form "Form_sbfrm" etc and not using a "!". If I change to "!" it bugs out.
Thanks for your help, KAL
Thanks Delecron,
I think I will stick with the tabs for now as they are giving me exactly what I want, but remember what you have said for when I make future improvements if its a better way of doing it.
EDIT
Using what you have said I changed my VBA to a DCOUNT method:
Dim j As Integer
j = DCount("*", "qry_CurrentProjects", "FK_Project_Client_ID = Forms!Navigation!Navigationsubform.form!Client_ID")
Form_frm_Clients.ClientTabs.Pages("Current Projects").Caption = "Current Projects (" & j & ")"
This means my report tabs are now also working just how I wanted
I was getting in a muddle with the criteria/filter, hense the edit.
If Recordset is an old method I am assuming it would be best to replace my other code with the Dcount method?
Thanks again, KAL
Further EDIT
After doing this I could see that everytime the form was changed there was a slight flicker. Not bad but you could see there was a lot of calculation going on. Therefore I have changed my method to the following, and posted here for anyone looking at this in the future.
In the form footer a textbox with COUNT([Project_ID])
In my function
Dim j As Integer
j = Form_frm_Clients!rpt_CurrentProjects.Report!txt_CurrentProjectsCount.Value
Form_frm_Clients.ClientTabs.Pages("Current Projects").Caption = "Current Projects (" & j & ")"
Now I can see it is working quicker with no flicker.
Recordset if you need to return complex data, if you need one value, a total or a sum, Domain functions are the way to go. Don't overdue them though, having too many on a form or a report can start to bog down usability.
Glad I can help.
Recordset.Recordcount is a legacy feature that only worked in ADP files (Access front end's to a SQL database). Those are no longer supported.
If the report is based on 1 client only and there is no grouping then you can do this:
Click on the detail section and in Events create an event for On Paint. In there set
(Name of Page).Caption = DCount("*", "NAME OF QUERY/TABLE") or
(Name of Page).Caption = DCount("*", "NAME OF QUERY/TABLE", "Filter Expression") (Filter expression optional).
If the report is grouped where it will show a different page per client or date range or any other grouping this will not work since the Caption field is not data bound. You would have to add logic to the Dcount statement above to field by the current filter condition.
For example, say you have a database of 200 clients and you're running one big report on all of them, each page will get its own tab control per client, the syntax would be
(Name of Page).Caption = DCount("*", "ClientContacts, "ClientID = " & ClientID)
The better way to do it especially if you are grouping is get rid of the tab control and use databound controls. You could create a box around the information that would be in the tab page and put a textbox where the tab would go. Create a group header for however you are grouping the data. Create another invisible textbox in the group header and set the controlsource = Count([fieldname]) where fieldname is whatever you are grouping the data by (the inside brackets count).
Then in the textbox you created to simulate the tab, set the controlsource to the name of the invisible textbox.
Let me know if this helps.

MS Access 2013 copy a specific number of fields and paste into a new record

I have found similar answers to this question, even on this site, however, the syntax has not worked for my database and I'm not sure what needs to be done. This data base is used to house audits for staff performance and accuracy. I am now in the midst of creating the forms and getting them to flow properly for the user.
When conducting an audit, the user will need to enter six specific fields into the first form. Those forms are Audit, Month, Year, Username, Location, Reviewer, and Date. The user will need to complete multiple audits, however, these six fields will always be the same.
I would like to copy these fields in the first form and carry them into the second form so the user does not have to repeat the information. Here is my current code (set to run on the click of a command button on the bottom of screen 1):
Dim strSQL As String
strSQL = "INSERT INTO [tblTripMem] (Audit, Month, Year, Username, Location, Reviewer, Date)"
strSQL = strSQL & " Values (" & Me.cboFP1Audit & "," & Me.Month & "," & Me.Year & "," & Me.Username & "," & Me.Location & "," & Me.Reviewer & "," & Me.Date & ") FROM [FPScreen1]"
strSQL = strSQL & "WHERE (currentrecord = " & Me.CurrentRecord & ")"
DoCmd.RunSQL (strSQL)
Each time I run this I receive the following error: "Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.
I am new to Access and am unsure of what this means or how to fix it. All I know is that I'm not finding a solution. Can anyone help? I'd greatly appreciate it.
Here's a mock-up Access file illustrating a way to do what you're doing without using SQL:
With Form 1 open...
...complete the various fields:
Click the Copy to Form 2 button and this will open Form 2 and populate its fields with the data from Form 1:
Here's the VBA code on the Copy to Form 2 button's OnClick event:
Private Sub cmdCopyToFrm2_Click()
Dim frm As Form
DoCmd.OpenForm "Form2"
Set frm = Forms!Form2
With frm
!AuditRef = Me.cboFP1Audit
!AuditMonth = Me.txtAuditMonth
!AuditYear = Me.txtAuditYear
!AuditUsername = Me.txtAuditUsername
!Location = Me.txtLocation
!Reviewer = Me.txtReviewer
!AuditDate = Me.txtAuditDate
End With
End Sub
Note that when Form 2 opens, the textbox that the cursor defaults to might not seem to show any data; if you move away from that textbox it should magically show (don't know why it does this, but there you go).
INSERT INTO table (...) VALUES (...) cannot have a FROM or WHERE clause. You insert a single record with fixed values, not data from another table.
But once you delete these clauses, you will have other errors, because you need to format your string and date values correctly to get the INSERT query to work.
And then you will still be prone to SQL injection errors. It is safer to use Recordset.AddNew and .Update to add records.
See e.g. here: https://stackoverflow.com/a/34969410/3820271
(but without the loop)

combobox data from 2 related tables Ms Access

i have 2 tables : Salesagent and Client which are related by id, each sales agent have too many clients with the same id ,
i want to add combo box to display the salesagent, then another combo box that displays the clients of that salesagent
combosale is ok ..
comboclient , displays the 1'st field of client table(only one not all of them ) ,when choosing only 1'st salesagent
it displays nothing when i choose another salesagent even if it has clients related to it
:(
i used :
Me.combmoclient = DLookup("[cname]", "[client]", "[salesagent]= '" & Me.Combosale & "'")
Don't use Dlookup, it will just return the first value that matches your criteria, when really you need the whole set of clients for that sales agent. Instead you should use the AfterUpdate() event of the combosale field to do something like this:
Private Sub Combosale_AfterUpdate()
Me.comboclient.RowSource = "SELECT cname FROM client WHERE id = " & Me.Combosale.Column(1) & ";"
End Sub
In general, pure SQL queries are much faster than the Dlookup, Dsum, etc. functions. You will have a much more stable application if you stay away from them and write SQL code into your Access VBA.
this vba solved the problem :)
Private Sub Combosale_AfterUpdate()
Me.comboclient.RowSource = "SELECT cname FROM client WHERE id = " & Me.Combosale.Column(1) & ";"
End Sub
tooo many thanx for your help !!

Microsoft Access Database - Search textbox form

I am trying to create a form which contains a textbox and a button to click on to search for a record in a specific table and show all pertaining information for the searched text. With this form I will be using it as a sub-form so I think VBA is probably the best way.
Here is my Table:
Here is an example of what I would like to see happen:
I would like to enter a partno and click on the button and the fields will populate.
Please advise how to approach this.
On the click of the button you can set the SubForm's Recordsource to be based on the Query. It should be something like.
Private Sub Command0_Click()
Me!subFrm_searchResult.Form.RecordSource = "SELECT theFields " & _
FROM theTable " & _
WHERE partNoFieldName = '" &
Me.partNumberTextBoxName & "'"
End Sub
This should be a start for you.

MS Access search for record by textbox instead of dropdown

I'm pretty new to MS Access. I'm trying to create a simple form that will basically search for a particular record using a textbox, rather than a drop down box. Essentially a user would be able to enter an ID number and retrieve some other related Info. However, I do not want the user to be able to add any new records to the database. I've been able to get the forms to look the way I want them, but I'm not sure where to place the code (do I create a macro, insert the code into the properties of the button?) Any help is greatly appreciated!
I assume that you have bound your form to a table or a query and that you want to be able to enter the ID manually in a textbox, then press ENTER and load that record's data or display an error message if there is no such record.
As dsteele said, make sure that the form's Data property Allow Addtions is set to No to disallow users from adding records.
Then, from the AfterUpdate event of the textbox, add the following code (assuming that your textbox is named txtGoTo):
Private Sub txtGoTo_AfterUpdate()
If (txtGoTo & vbNullString) = vbNullString Then Exit Sub
Dim rs As DAO.RecordSet
Set rs = Me.RecordsetClone
rs.FindFirst "[ID]=" & txtGoTo
If rs.NoMatch Then
MsgBox "Sorry, no such record '" & txtGoTo & "' was found.", _
vbOKOnly + vbInformation
Else
Me.RecordSet.Bookmark = rs.Bookmark
End If
rs.Close
txtGoTo = Null
End Sub
Note that you will have to change the line rs.FindFirst "[ID]=" & txtGoTo to something that is adequate for your data:
"[ID]=" should be replaced by the field you want to search (it could be "[POReference]=" or something else.
if you are searching by a numeric ID, for instance because the field is an autonumber column, then the code is fine.
Otherwise, if the field you are searching on is a string (say PN12-G) then you have to change the code to:
rs.FindFirst "[ID]=""" & txtGoTo & """"
Failing to use the proper quoting (or quoting where not necessary) will result in errors of the kind Data type mismatch....
As a new user, I would recommend that you have a look at the sample NorthWind project database that is either shiped with older versions of Access or available as a template for download from Access 2007.
There a lots of techniques to learn from as a new Access developer, including other ways to implement record navigation.
Set the form property Data/'Allow Additions' to No.
Either in the AfterUpdate event of the textbox, or in the Click event of a button, you can write code or assign a macro to look up and display the record you want.