We have a fairly simple multi-user database that we use to make Purchase Orders. The PO Number is generated from an AutoNumber field.
Sometime in the last 4 days something happened that made the numbers go from 8518 to 17474. I know that a user can't change this number. I am just wondering what could have caused this?
There are no records in between 8518 and 17474 to show that 9000(ish) records have been made. I am very confused!!
Autonumber fields in Access are updateable for new records. A user can just write a value to the autonumber column, and Access will continue numbering from there.
For example, a query like this could do it:
INSERT INTO [Purchase Orders]([PO Number]) VALUES (17473)
That will write that value to a new record, and Access will continue on from there.
Also, when copy-pasting, Access will create new autonumbers. The following actions will increment your autonumber seed by the number of records in the table:
When in table view:
Ctrl + A (Select all)
Ctrl + C (Copy)
Move to new record, select entire row
Ctrl + V (Paste all records)
Escape (oops, didn't mean to copy table)
No new records would've been added since the action was canceled, but only after already generating autonumbers for all those new records.
Related
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. :)
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.
I have a MS 2010 Access Report that needs to be populated by records that a user pre-chooses. For example.
Form1 has 2 fields, LOT# (which is record id) and CheckoffBox (unbound).
User checks which Lot#'s (records) he wants displayed, then clicks REPORT button. Report only shows selected records.
Can someone help me create the code?
In order to allow the user to use a check box to select multiple records, the list presented in form 1 must be based on a table that has LOT# and a yes/no field. (ie form 1 must be based on a query or a table that ahs this yes/no field).
If only one user will ever use this at any one time then you can simply add a yes/No field to the table that has all the LOT# values.
On your report you then only print those lot numbers that are checked.
Your report simply has to have SQL with a where clause that only print records that have the Yes/No field ticked. (=true =-1).
If many users are going to use this form at the same time it gets more complicated as obviously they all need to have their own "set of yes/no fields".
So you would need to copy the table with the LOT# into a temp table for use by each user (it might have a primary key of USERID, LOT#, or it might be a table with just LOT# and yes/no fields, that only a user can access - ie in their own copy of the database file that has the front end forms).
Anyway, assuming it's a single user, creating the above should be quite straight forwards.
On opening form 1, you might use the form_open event to run a SQL statement that sets all the Yes/No values to No. Although you might not want to do this.
Use
docmd.SetWarnings false
Docmd.runsql "UPDATE theTable SET YesnoField = 0 WHERE YesnoField = -1;"
docmd.SetWarnings true
Let me know if you can take it from here.
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.