Hoping someone can assist here, I'm fairly new to SQL but yet the most experienced person in the office so this job has fallen to me.
I'm trying to build a form that will insert customer orders into production scheduling. The form allows users to select a machine from the machine list table, however what I need it to do after that is find the last job number for that specific machine and show the next sequential number in a text box; and that's where I'm stuck. The goal is that when the production user is adding an order to the database, by selecting their machine the next available job number is automatically populated. The information entered will be saved to a master scheduling table.
I've got a query built that pulls the entire list of machine and job combinations, as my goal was to build a macro that could search from that list, but so far I haven't gained any traction. Any help/advice would be appreciated!
Welcome to SO.
My suggestion would be to create a table to hold the sequence numbers. For the sake of this example, let's call it ProdSeq, which means Production Sequences. As part of this table definition, I would use Data Macros (Access 2010 and up) in order to assign the sequences as records are added. I would use a Unique index in order to ensure no duplicates are created.
Table: ProdSeq (Field Definitions)
MachineID (Number - Long) - References Machine ID in Machines Table
ProdSeq (Number - Long) - Incremented for each machine
OrderID (Number - Long) - References Order ID in Orders Table
Indexes
Under the Design ribbon tab when designing the ProdSeq table, click the Indexes button.
Create an Index called UniqueKey
Row 1: Index Name = UniqueKey, Field Name = MachineID
Row 2: Index Name = Leave Blank, Field Name = ProdSequence
Click on Row 1, Column 1 and set the following Index Properties:
Primary = Yes
Unique = Yes
Ignore Nulls = No
Data Macros
Under the Design ribbon tab when designing the ProdSeq table, click the Create Data Macros button, and then the Before Change button. Enter the following data macro: (Pastebin link)
Create the Before Change data macro and set it as follows:
If [IsInsert] Then
SetLocalVar
Name LatestProdSequence
Expression = 0
Look Up A Record In ProdSeq
Where Condition =[ProdSeqLookup].[MachineID]=[ProdSeq].[MachineID] And
[ProdSeqLookup].[LatestSeq] = True
Alias ProdSeqLookup
SetLocalVar
Name LatestProdSequence
Expression =[ProdSeqLookup].[ProdSequence]
SetField
Name ProdSeq.ProdSequence
Value = [LatestProdSequence]+1
SetField
Name ProdSeq.LatestSeq
Value = True
End If
Pay special attention to the fact that only one SetLocalVar is within the LookUpRecord clause. Use the collapse / expand (-/+) button on LookUpRecord to make sure.
Create the After Insert data macro and set it as follows: (Pastebin Link)
For Each Record In ProdSeq
Where Condition = [ProdSeqFlagFix].[MachineID]=[ProdSeq].[MachineID] And
[ProdSeqFlagFix].[LatestSeq]=True And
[ProdSeqFlagFix].[ProdSequence]<>[ProdSeq].[ProdSequence]
EditRecord
SetField
Name ProdSeqFlagFix.LatestSeq
Value = False
End EditRecord
Test it Out
You can create this in a blank database in order to see what I am talking about. You should be able to adapt it to your specific situation.
Form
On your form, when the user selects a machine and order, you can use VBA in order to check for an existing record in ProdSeq, and fetch the ID. If no record exists, then you can create one, and then return the ProdSeq ID to the form.
Note: Depending on your design, you may also need to create a Data Macro on the Schedules table. Suppose someone creates a schedule with a specific machine and order and reserves a production slot. Now assume they change the Order ID .. we have a production slot reserved in error. So if this applies, you'll also need an AfterUpdate data macro on the Scheduling table that checks to see if [old].OrderID <> [Schedule].OrderID - and if they do differ, to remove the Production slot from the schedule table and the Prod Sequence table.
As I understand, you need to add suggested value for job number when you add new record to the table. If so, you can use, for instance DMax function. Here is example of VBA code for this, it can be called when you add new record:
Me.MyTextBox = DMax("JobField", "JobsTable") + 1
I supposed that JobField, which contains job numbers has Number data type.
Also you can use this function inside any query as a calculated field.
Related
I have a two table scenario with a typical parent / child relational setup:
tblGroup - idGroup (autonumber, PK); GroupName (Short Text), Rank (Number)
tblRange - idRange (autonumber, PK), idGroup (FK -> tblGroup.idGroup), RangeName (Short Text), Rank (Number)
What I am doing on the parent (tblGroup) table is using a data macro to add the rank using the BeforeChange event:
IF
IsInsert
SetField - Rank
- DMAX(Rank, [tblGroup])+1
This works nicely and I can happily use a parametized INSERT query to add rows to the table and not have to worry about duplicate ranks and so forth.
What I would like to be able to do but cannot figure out how, is to have a data macro do the same thing for the child (tblRange) table, with the rank being set to the new highest for the parent group the child record belongs to.
If I use the same DMAX approach as I have above I am supposed to be able to set a criteria as a third option, acting like a where clause, to limit the lookup / calculation. How can I refer to the specific idGroup I am working with in tblRange in the macro? I cannot seem to figure out how to reference the new records value for this in the macro.
Something like DMAX(Rank, [tblRange], ???How_to_refer_to_idGroup_Properly???)+1
Any help greatly appreciated
Cheers
The Frog
I figured out a way to do this. Thankyou caffeinated beverages!
The reason for the strange error messages is due to limitations in the Data Macro processing, specifically in the BeforeChange event. The solution is as follows:
Create a query that selects MAX rank (MaxRank) and GROUP BY for the idGroup (ParentID)
The resultant query produces two columns of data: [MaxRank] and [ParentID]
There will be a row for every idGroup with the maximum Rank for each
Create a BeforeChange data macro
Set the following:
IF IsInsert
LookupRecord
Lookup Record In - qryGetMaxRank (or whatever you called your query)
WHERE - [qryGetMaxRank].[ParentID] = [tblRange].[idGroup]
Set Field
Name - [tblRange].[Rank]
Value - [MaxRank] + 1
The BeforeChange event cannot handle parameters for a query, and I am guessing that this applies in some form the to DMAX function here too. The use of a query that does not use any parameters, and then using the LookupRecord WHERE clause to do the filtering provided the single row result needed. The [MaxRank] value from the returned result is then able to be used to set a new value for the field.
Bit of a workaround but it does allow someone to work with the data either through a form or through the datasheet view and not create a problem.
**In answer to if this is a multi-user DB - it is not. It is just me working with it. If / when the solution is scaled up to something requiring multi-user I will likely recreate the BE in SQL Server or MySQL and use stored procedures for all data I/O. Happy to keep Access as the FE and compile into an application (using the runtime for clients), but I am a fair way off from having to do that yet. Very early stages of development at this time.
Cheers to everyone for the pointers. They helped me figure this out. Hopefully this will be of use to someone else in the future.
PS: If you need to use a parametrized query in a data macro it looks like the best bet is with the AfterInsert event or AfterUpdate event as they can support parameters.
Access 2016, table with a AfterInsert datamacro.
In a comment to a previous question that I can no longer find, Albert D. Kallal (user:10527) noted that if one uses the Set LocalVar approach to call a user-defined function in vba, that vba "session" does not see the newly inserted record.
Even if one passes in the identity of the newly added record, any queries referencing the table where the record was just added won't see the newly inserted record.
Has anyone developed a work around so that for example in building a closure-table, the newly added record is visible or can be used?
This is very similar to the problem Alberta Kallal has nicely shared solutions for of copying over an existing record using the "after update" approach to get around being unable to create a record within a for each loop. However, in this case I would like to use the result of a query as the basis for copying / inserting, not just copying over an existing row or 'hard coding' the business logic for the modifications into the datamacro (hence would be easy to do if vba approach could see the just added row).
Specific use case is trying to create a way of inserting "induced" records in an accounting application. One earns some money that has no tax deducted, so it is nice to have an automatic journal entry created showing a future liability to pay the tax. In other words, the presence of a record in a table should automatically generate additional records - and the business logic of those additional records is defined through queries.
Even more specifically, given a "transactions" table with fields RegisterID, AccountID, Amount, TrDate, and a "Induced Transaction Queries" table that specifies the queries to provide the induced transactions with fields AutoNumberId, QueryThatDefinesAdditionalTransactions (and multiple rows, e.g. "Query That adds self", "Query That Adds Tax Liability", "Query That Computes Sales Tax Portion"),
how can a datamacro create rows in a "Transactions For Analysis" Table based on iterating over the "Induced Transaction Queries" table and inserting the results of the query in each row applied to the newly added row in the original "transactions table"
Thx
Well, while calling VBA from the macro after insert event can’t get the row just inserted, that VBA routine can read + update as many OTHER rows as you please. And if that new row or data you write out in VBA has to include the data from the row just inserted?
Well pass the columns to the VBA routine. So it now can go add up all the other rows, and THEN include the values just passed from the data macro.
So the data macro (after insert) can look like this:
And the VBA code thus can look like this:
Public Function AfterU(vid As Variant, Amount As Variant)
Debug.Print vid, Amount
Dim rst As DAO.Recordset
' open table, sum data
' add Amount passed.
' write out data to some table.
' caution - don't add reocrds to this table that has the trigger
' else you wind up in a endless loop
End Function
The above of course has to be placed in a standard code module (not forms), and has to be defined as public as per above.
So while you find that the record JUST added is not yet committed to the table (it is about to be), you can still run + call some VBA code. You just not get your hands on the record just (about to be) inserted.
However, since you can pass the needed columns such as amount etc. to include in the final total? Then you are free to write as much VBA update and insert code as you wish. So you can pull some records, build a total, and now update some existing record, or even add a new record. Just include the new amount passed also.
As noted, you don’t want to “tangle” up writing to a table that has such a trigger with VBA inserts since you can easy get stuck a endless loop.
However, for adding up, or updating, or inserting to another table, you should be fine to do what you please in the VBA code.
First of all, I am a total NOOB! I am trying to make an Access DB for handling orders through an entire process. As such, I have created tables based on each of the individual processes. The order data, which holds only the basic information is in tblCurrentOrders. Each of the other processes is linked to tblCurrentOrders by the OrderNumber field. The first step of the process is due date information is entered in the tblPlanner table. Obviously, until data is entered in tblPlanner, no OrderNumber exists (this will hold true for the other tables, too, if I ever get that far).
I want to create a form based tblCurrentOrders that shows only the records without corresponding entries in tblPlanner (new orders) and then I want to be able to enter the tblPlanner info in a subform. I have tried making a form based on tblCurrentOrders with a subform based on tblPlanner, but I can't figure out how to only display new orders. I also tried basing the form on a query that only showed new orders, but I don't know how to make the subform based on tblPlanner to work.
Please Help!!
Well, the easiest way to link the tables would be to create your OrderNumber in the tblPlanner when you start a new order. Then add a flag and timestamp as to whether it's "released" yet.
EDIT
Since you provide a little bit more detail, I'll edit my response to more closely align for your desired approach.
Creating a "New Order" is a multi-step process. So it's usually best to create a Command Button on a form that calls VBA code. This will allow you to control each step and make sure it's correct.
Step A: First you want to:
1) Create a Control Form (if you haven't already) that allows you to put Command Buttons which will launch different VBA code or open different display Forms.
2) On the Control Form, create a List Box that allows you to select an existing OrderNumber.
3) On the Control Form, create a Command Button to open an Order Form which uses the selected List Box OrderNumber. When that Order Form opens, it will populate with the tblCurrentOrders data for that OrderNumber and also populate the subform with tblPlanner data. (As long as you have them linked properly.)
4) On the Control Form, create a Command Button to open the Order Form with a set of records which are "New Orders" only. See the more detailed process below in Step C.
5) On the Control Form, create a Command Button to Launch VBA code that will create a "New Order". This is a multi step process detailed below in Step B.
6) Create any other buttons or controls that allow you to monitor or advance your "Order" along the way to completion. (This is a ton of work to get all the pieces in place.)
Step B: When you press the Command Button to create a "New Order" you want to create VBA code that will:
1) Create a new record in the tblCurrentOrders table.
2) Create a Unique OrderNumber on the new Record. It's usually best if you control the generation of this number and don't just let it be a system generated sequence number. But whatever you desire is ok as long as it's Unique.
3) Set your ReleasedFlag to false on the new tblCurrentOrders record.
4) Make sure your ReleasedTimeStamp is null. (Or whatever value you want it to be.)
5) You may want a CreatedTimeStamp which you can populate with a date of Now().
6) Populate any other "Initalization" fields that need to be filled. (Like Backorder status, Return flags, Shorted Flags, etc. etc. etc.)
7) Create a new record in the tblPlanner table.
8) Copy the Unique OrderNumber that you created for the tblCurrentOrders record into the OrderNumber field on the new tblPlanner record. This creates a link for you to use with your subqueries and subforms.
9) Now you can open the Order Form with this new OrderNumber.
Step C: When you press the Command Button to open a set of records which are "New Orders" only:
The Command Button needs to launch a query to find "...tblCurrentOrders that shows only the records without corresponding entries in tblPlanner (new orders)":
You just need to select tblCurrentOrders that have a ReleasedFlag set to false.
`SELECT * FROM tblCurrentOrders WHERE ReleasedFlag = false`
So when you say: "...and then I want to be able to enter the tblPlanner info in a subform"... you can create a subform linking to tblPlanner based on the tblCurrentOrders OrderNumber field.
This is all reliant on you observing that when you say "...records without corresponding entries in tblPlanner..." That you really mean: records without released entries in tblPlanner. And that means: in order for a record to exist in tblCurrentOrders, it has to have a corresponding blank (or starter) record created in tblPlanner. Thus now you can display blank tblPlanner records that are linked to unreleased tblCurrentOrders records.
Then once your data entry people are done monkeying around with the New Order, they can "Release" the order (usually by clicking on a Release Command Button). At that point, you can set your ReleasedTimeStamp to Now() and set your ReleasedFlag to True in the tblCurrentOrders. It's officially no longer a "new order" and is now a live order in your system.
You are at the tip of the iceberg for creating a home grown order entry system. The complexities for building a good one are immense. Best of luck figuring it all out. Just remember to use time stamps and ID fields so you can go back and un-do what may have been done by accident.
Hope this all helps. :)
guys
' i am beginner in access 2007 and i want to create a form that contains many fields (product id, product name, etc and date of transaction) and use a query to search for data
in other words for example i want to enter in this form a date range i.e from 1/1/2013 to 1/03/2013 and search for product x ( attention ) my basic table contains only date of transacton field and not the from, to fields ( the from , to fields i want only to add them in the search form and them to search based on the value or date of transaction field ) please help me
Short but sweet answer;
Create a new "Query" using the GUI. Add your table to the top part. Double-click columns in the table to add them to the output of the Query.
Next, in the query conditions (grid below the name of each field) use brackets "[]" around your from/to dates. E.g. the query condition underneath your date field may be;
"between [MyStartDate] and [MyEndDate]".
Now "run" the query to test it; Access will prompt you for 'MyStartDate' and 'MyEndDate'.
Finally; if you save this query and set it as the "Data Source" for a Form, you may alter the above condition slightly to pull the values automatically from the form itself, so that you are not prompted every time the query runs. E.g. this condition may be;
"between Forms![MyTableForm]![MyStartDate] and Forms![MyTableForm][MyEndDate]".
You will have to play with it a little, but those are the basics.
I have table in MS Access that has an AutoNumber type in field ID
After inserting some rows, the ID has become 200
Then, I have deleted the records in the table. However, when I tried to insert a new row, I see that the ID starts with 201
How can I force the ID to restart with 1, without having to drop the table and make new a new one?
In Access 2010 or newer, go to Database Tools and click Compact and Repair Database, and it will automatically reset the ID.
You can use:
CurrentDb.Execute "ALTER TABLE yourTable ALTER COLUMN myID COUNTER(1,1)"
I hope you have no relationships that use this table, I hope it is empty, and I hope you understand that all you can (mostly) rely on an autonumber to be is unique. You can get gaps, jumps, very large or even negative numbers, depending on the circumstances. If your autonumber means something, you have a major problem waiting to happen.
In addition to all the concerns expressed about why you give a rat's ass what the ID value is (all are correct that you shouldn't), let me add this to the mix:
If you've deleted all the records from the table, compacting the database will reset the seed value back to its original value.
For a table where there are still records, and you've inserted a value into the Autonumber field that is lower than the highest value, you have to use #Remou's method to reset the seed value. This also applies if you want to reset to the Max+1 in a table where records have been deleted, e.g., 300 records, last ID of 300, delete 201-300, compact won't reset the counter (you have to use #Remou's method -- this was not the case in earlier versions of Jet, and, indeed, in early versions of Jet 4, the first Jet version that allowed manipulating the seed value programatically).
I am going to Necro this topic.
Starting around ms-access-2016, you can execute Data Definition Queries (DDQ) through Macro's
Data Definition Query
ALTER TABLE <Table> ALTER COLUMN <ID_Field> COUNTER(1,1);
Save the DDQ, with your values
Create a Macro with the appropriate logic either before this or after.
To execute this DDQ:
Add an Open Query action
Define the name of the DDQ in the Query Name field; View and Data Mode settings are not relevant and can leave the default values
WARNINGS!!!!
This will reset the AutoNumber Counter to 1
Any Referential Integrity will be summarily destroyed
Advice
Use this for Staging tables
these are tables that are never intended to persist the data they temporarily contain.
The data contained is only there until additional cleaning actions have been performed and stored in the appropriate table(s).
Once cleaning operations have been performed and the data is no longer needed, these tables are summarily purged of any data contained.
Import Tables
These are very similar to Staging Tables but tend to only have two columns: ID and RowValue
Since these are typically used to import RAW data from a general file format (TXT, RTF, CSV, XML, etc.), the data contained does not persist past the processing lifecycle
I think the only ways to do this is outlined in this article.
The article explains several methods. Here is one example:
To do this in Microsoft Office Access 2007, follow these steps:
Delete the AutoNumber field from the main table.
Make note of the AutoNumber field name.
Click the Create tab, and then click Query Design in the Other group.
In the Show Table dialog box, select the main table. Click Add, and then click Close.
Double-click the required fields in the table view of the main table to select the fields.
Select the required Sort order.
On the Design tab, click Make Table in the Query Type group. Type the new table name in the Table Name box, and then click OK.
On the Design tab, click Run in the Results group.
The following message appears:
You are about to paste # row(s) into a new table.
Click Yes to insert the rows.
Close the query.
Right-click the new table, and then click Design View.
In the Design view for the table, add an AutoNumber field that has the same field name that you deleted in step 1. Add this AutoNumber
field to the new table, and then save the table.
Close the Design view window.
Rename the main table name. Rename the new table name to the main table name.
I always use below approach. I've created one table in database as Table1 with only one column i.e. Row_Id Number (Long Integer) and its value is 0
INSERT INTO <TABLE_NAME_TO_RESET>
SELECT Row_Id AS <COLUMN_NAME_TO_RESET>
FROM Table1;
This will insert one row with 0 value in AutoNumber column, later delete that row.