Access - Open different report from one button - ms-access

How I can open diferents reports from one button in access if that form that shows me the information has been filtred. For example, in one form I have 2 elements, "t_element"=3 means is ID and name of report is "DNI_CAB", when "t_element"=54 means is Table and name of report is "Table_CAB". And if I filtred another form maybe shows me 8 elements. Thanks!

If I'm understanding this properly, you need to make this table-driven. By that, I mean you need to set up a table with 2 fields; ID and Report Call it tblReports.
Then you would do something like this on the OnClick event of the button:
Dim db as Database
Dim rec as Recordset
Dim MyReport as String
Set db = CurrentDB
'Find the Report you're going to use by filtering by the ID you want
Set rec = db.OpenRecordset("Select Report from tblReports where ID = " & me.txtID & "")
'Fill a variable with the resulting value
MyReport = rec(0)
'Now that we have the report name, open it
DoCmd.OpenReport MyReport
This is all entirely aircode, written off the top of my head, so it probably needs to be altered a little. But it should give you an idea of how to go about writing the code to get this done.

Related

How to display record inside form Access 2016 - VBA

Hope you're enjoying your Friday afternoon!
I've got a form on MS Access which searches a linked table for a barcode (which is entered by the user)
If the barcode exists in the table I'd like to show the user the record which contains the matched barcode, if not the code moves on elsewhere.
Here is what I have so far:
DoCmd.DeleteObject acQuery, "Query2"
Set qdef = CurrentDb.CreateQueryDef("Query2", s)
Me.sbfMatchedRec.SourceObject = "Query2"
I get an error when trying to change the SourceObject to Query2.
If I open Query2 it has the exact information I need in it. I can also go via the form properties and change the SourceObject to Query2 which then displays what I need, but I just need to know how to change this in VBA as above.
Thanks!
You could requery the subform with the barcode passed in from the form's textbox as the WHERE criteria in the subform's .RecordSource property.
For example, say this table (tblProducts) has your list of barcoded records:
You could then add a subform to your form that will show records from tblProducts. Also add a textbox to the form for the user to supply a barcode and a command button for the user to initiate a search:
Before hooking-up the search button with the VBA, take a look at the .RecordSource property for the subform...
...switch the query builder to SQL View:
Copy the sql as you can use this as the basis to filter the records in the subform using VBA.
Go back to the form in design view and go in to the search button's On Click event:
The SQL you've copied can then be used to create an SQL string that takes the value entered in the form's barcode textbox (I've called the text box on the form txtBarcode) as part of the WHERE clause. This sql string can then be applied to the subform's .RecordSource property and then the subform can be requeried to show the result set of the new SQL definition in the subform:
Private Sub cmdSearch_Click()
Dim strSql As String
strSql = "SELECT tblProducts.Barcode, tblProducts.ProductName" _
& " FROM tblProducts"
If _
Me.txtBarcode > "" _
Then
strSql = strSql & " WHERE tblProducts.Barcode=" & Me.txtBarcode
End If
Me.tblProducts_sub.Form.RecordSource = strSql
Me.tblProducts_sub.Form.Requery
End Sub
So if we put 1001 in the text box on the form, and click the search button, the subfom only shows that matching record:

How to set an Access Tab Control's page name by VBA

I have a form in MS Access with a Tab Control (called TabCtrl). This control has several pages, each with a subform.
On Form_Open, I want to query the subforms for the total number of records and put that number in the tab's name. For example, the tab named MyTab should become MyTab (2):
Private Sub SetTabName_MyTab()
Dim i As Integer
i = CurrentDb.OpenRecordset("Select count(*) from [MyQry];").Fields(0).Value
TabCtrl.Pages("MyTab").Name = "MyTab (" & i & ")"
End Sub
However, when I run this, the last line returns Run-time error 2136 "To set this property, open the form or report in Design view". Does this mean I can't do this in code? Should I use another Event?
You are trying to change the internal name of the control, rather than caption on the tab page control.
Try:
ATabcontrol.Pages("MyTab").Caption = "MyTab(" & i & ")"
Note: I have done this before and found issues with the text not changing till the tabcontrol was manipulated.
Try:
Dim s as string
'To Get current Tab Caption
s = Me.TabCtl.Pages(Me.TabCtl.Value).Caption
'To Set current Tab Caption
s = "TabName"
Me.TabCtl.Pages(Me.TabCtl.Value).Caption = s

How to directly update a record in a database from a form number (Access 2007)

I have a job-tracking system, and there is a query that returns results of all jobs that are overdue.
I have a form that displays each of these jobs one-by-one, and has two buttons (Job has been completed, and Job not completed). Not completed simply shows the next record.
I cannot find a way to get access to the current record to update it's contents if the "Has been Completed" button is pressed, the closest I can get is the long number which represents the records position in the form.
The VBA to get the index of the record in the form is as follows.
Sub Jobcompleted(frm As Form)
Dim curr_rec_num As Long
curr_rec_num = frm.CurrentRecord
End Sub
This is my first shot at VBA, and after an hour of searching I cannot find anything to solve my problem.
Am I going about this the entirely wrong way? Working in Microsoft Access 2007
Further Info All tables are normalized
Vehicle Table: Contains vehicle_id(pk), as well as rego and model etc
Job Table: Contains job_id(pk), vehicle_id(fk) and other info about what needs to happen, as well as the next occurance date, days between each occurance of the job (all jobs repeat) and other info
Job History Table: Contains job_history_id(pk), job_id(fk), date completed and comments
When the job completed button is pressed, it should create a new entry in the job history table with the current date, any comments and the job id
This is the script I am trying to get working
Private Sub Command29_Click()
Dim strSQL1 As String
Dim strSQL2 As String
Set Rs = CurrentRs
Set db = CurrentDb
strSQL1 = "INSERT INTO completed_jobs(JOB_ID, DATE_COMPLETED, COMMENTS) VALUES " & Rs!job.ID & ", " & Date
db.Execute strSQL1, dbFailOnError
strSQL2 = "UPDATE job SET JOB_NEXT_OCCURANCE = JOB_NEXT_OCCURANCE+JOB_RECURRANCE_RATE WHERE job.ID = Rs!job.ID"
db.Execute strSQL2, dbFailOnError
End Sub
Note: Line Set Rs = CurrentRs is completely incorrect, I believe this is what I need to figure out? This is called on button-press
I am posting an image which shows the form (non-continuous).
#HansUp, I get what you are saying, but I dont quite think it's applicable (I did not provide enough information first time around for you to understand I think)
#sarh I believe this Recordset that you are talking about is what I need, however I cannot figure out how to use it, any hints?
#Matt I am 90% sure I am using a bound form (Like I said, new to Access, been looking at everything people have suggested and learning as I go). There is of course an ID for the job (Just not shown, no need to be visible), but how would I access this to perform an operation on it? SQL I can do, integrating with Access/VBA I am new at
As I understand your situation, your form is data-bound bound (you can get record index), so - your form already located on this record. If you need to update some field of underlying dataset, you can write something like
Me!SomeField = ...
DoCmd.RunCommand acCmdSaveRecord
If your form has control bound to "SomeField", then the form will be updated automatically.
If this will not help, you can look to a couple of another directions:
1) Update records using SQL code. For example, you have ID of record that should be updated in the form data set, so you can write something like:
Call CurrentDB.Execute( _
"UPDATE SomeTable SET SomeField = SomeValue WHERE SomeTableID = " & Me!SomeTableID, dbSeeChanges)
2) You can look at the Bookmark property - both Recordset and Form has this property, it describes the record position. So you can write something like this (not the best example, but can help you to get an idea):
Dim Rs as Recordset
Set Rs = Me.RecordsetClone 'make a reference copy of the form recordset
Rs.Bookmark = Me.Bookmark 'locate this recordset to the form current record
Consider a simpler approach. I doubt you need to be concerned with the form's CurrentRecord property. And I don't see why you should need a command button for "Has been Completed" and another for "Has not been Completed".
Add a "Yes/No" data type field to the table which is used by your form's record source. Set it's default value property to 0, which represents False or No. Call it "completion_status". Create a new form using that record source. Then your form can have a check box control for completion_status.
Newly added records will have False/No as completion_status --- the check box will appear unchecked. The completion_status for other records in the forms can be toggled between Yes (checked) and No (unchecked) using the check box control.

MS Access 2007 OpenForm method, can't get the where clause to produce the correct result

I can not get the OpenForm method to open a form with the correct record loaded. I'm going to do my best here to provide the details:
The 'source' form is based off Table A, and it is read-only. A button on the source form is being used to open a 'target' form that is used for editing records, also from Table A.
I have tried using the wizard to create the button that opens the form based on primary key equality. The result from the wizard is that no matter what record is in context on the source form, only the first record in Table A is ever loaded by the target form.
I have tried using a procedure with the following variations:
Dim frm As String, whr As String
frm = "Target Form"
whr = "Forms![Source Form]!ID = Forms![Target Form]!ID"
'whr = "[ID] = [ID]"
'whr = "[ID] = Forms![Target Form]!ID"
DoCmd.OpenForm frm, acNormal, , whr, , , 1
I could either get only the first record to load in the target form or get a new record to load in the target form. But I can not get the source form's loaded record to determine the record loaded into the target form.
Thanks for any help
I think you got close. You want the WhereCondition to be the same as a WHERE clause for a query of Target Form's record source, but without the word WHERE.
Dim frm As String, whr As String
frm = "Target Form"
whr = "[ID] = " & Me.ID
Debug.Print "whr: " & whr
DoCmd.OpenForm frm, acNormal, , whr
I intended Me.ID as the value of a control whose name is ID and is bound to a field in the current record of Source Form. Me is shorthand for "this form". One reason it's useful is because you wouldn't have to revise your code if you later decide to give the form a different name.
I added the Debug.Print statement so you can switch to the Immediate Window (Ctrl+g), and copy the whr string, then paste it into a new query based on the same record source which Target Form uses. That could be helpful in case you still don't get the correct record displayed when Target Form opens.
Your version also included 1 as OpenArgs to OpenForm. I didn't see how you were using that, so left it off. If Target Form includes an event procedure which does something with OpenArgs, make sure it doesn't override your WhereCondition.

How To Refer To Continuous Subform Contol

I have an Access 2003 form with one subform, set to continuous forms, in a subform control. For one record in the main form, 1 to many records will appear in the sub form. The data displays properly.
The main form is named Widgets and the sub form is named Transactions. There are 5 textbox controls that display the data in the subform. The one in question is ReceiptDate.
What I would like to do is look at the values and determine if there was a receipt for the year 2009, and if so then change the background of that row to yellow so it stands out when the user encounters that condition. Maybe even change the date field's font to boldface..
I tried many ways of referencing the subform's controls. When I have tried Me.Transactions.ReceiptDate I have only received the first record in that subform. I'd like to be able to loop through them and see if the condition is met. I tried Me.Transactions.ReceiptDate(1) and Me.Transactions.ReceiptDate(0) and so forth.
I tried the For Each ctl In Form.Controls route as well. It worked for a few iterations and then I received a run-time error 2455 "You entered an expression that has an invalid reference to the property Form/Report".
I had the subform in "datasheet" mode but thought that was causing me not to be able to read through an array of subform controls. So I changed it to "continuous" mode. I get the same errors for either.
Is there a way to reference specific "rows" in the subform and do something based on a value found? Also, I am performing this in the On Current event as I dont know where else to put the code. The subform loads before the parent form so its possible that these controls arent even fully "there" but then I do get the first row's date when I try it in the Immediate Window.
UPDATE 12.23.2010:
With the gracious help of #Remou I am able to debug.print the ReceiptDate fields from the RecordSet. This is great because now I can evaluate the data and do certain things based on the values.. The #Remou's code helped me put this into the OnCurrent event:
Dim i As Long
Dim frm As Form
Dim rs As DAO.Recordset
' Get the form and its recordset.
Set frm = Me.Form
Set rs = frm.RecordsetClone
' Move to the first record in the recordset.
rs.MoveFirst
' Move to the first selected record.
rs.Move frm.SelTop - 1
' Enumerate the list of selected records presenting the ReceiptDate field
For i = 1 To rs.RecordCount
Debug.Print rs![ReceiptDate]
rs.MoveNext
Next i
So now that I am able to know which row in my subform has a receipt from 2009, I need to be able to highlight the entire row or rows as I come across them in that for loop. How can I reference the actual row? Datasheet view or Continuous Forms view - I have tried both.
Conditional Formatting is great but it only allows me to highlight one particular record and I'd much rather be able to do this via VBA because...... from here I will want to give the use the ability to click on any record in the subform and get the receipt details and potentially print them.
Any ideas?
In this situation, it is best to use conditional formatting.
To refer to a control on a subform, refer to the subform control by name, then the form property to get the form contained, then the control by name:
Me.MySubformControlName.Form.MyControl
See: http://www.mvps.org/access/forms/frm0031.htm
I have finally got it. The frm.SelTop = x will set the selected record and from there I can set the background or font style, etc.. Very cool. A simple test for 2009 and setting the selected record:
Dim i As Long
Dim frm As Form
Dim rs As DAO.Recordset
' Get the form and its recordset.
Set frm = Me.Form
Set rs = frm.RecordsetClone
' Move to the first record in the recordset.
rs.MoveFirst
' Move to the first selected record.
rs.Move 0
' Enumerate the list of selected records presenting
' the CompanyName field in a message box.
For i = 1 To rs.RecordCount
If Year(rs![ReceiptDate]) = 2009 Then
frm.SelTop = i '<-----------------------------
End If
rs.MoveNext
Next i
In order for me to get the email off the bottom of my continuous form, I used this much simpler code (as I avoided the RecordsetClone code)
Me.[email subform].Form.SelTop = Me.[email subform].Form.Count 'selects the last row
str = Me.[email subform].Form.Email 'capture the value of the last row
MsgBox str