473,419 Members | 1,838 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,419 software developers and data experts.

Create new row in table

675 512MB
I want to have an "Edit" form=fEditLoc for rows in a subform=subfShowLoc. Once the form opens, I want to be able to create a new record in the table=tLoc which I will then edit.

Or to put it another way, I want to edit a record, and then do a "Save As" to a new record. Seems simple, but I can't keep the data in all the fields when I move the form to the NewRecord position. So how do I do this?
Apr 8 '09 #1
16 3164
ADezii
8,834 Expert 8TB
@OldBirdman
Hello OldBirdman, try this out and see what happens:
Expand|Select|Wrap|Line Numbers
  1. 'Select Current Record
  2. DoCmd.DoMenuItem acFormBar, acEditMenu, 8, , acMenuVer70
  3.  
  4. 'Copy Current Record
  5. DoCmd.DoMenuItem acFormBar, acEditMenu, 2, , acMenuVer70
  6.  
  7. 'Paste Append Record
  8. DoCmd.DoMenuItem acFormBar, acEditMenu, 5, , acMenuVer70
Apr 8 '09 #2
OldBirdman
675 512MB
Thank you. These tools will work for this.

Just curious, but I think somewhere I read that DoMenuItem was to be avoided if possible. The relative position of the items may change, or something. Is this something I should be concerned about?
Apr 8 '09 #3
OldBirdman
675 512MB
I think I replied too quickly. I would like my "Save As" to leave the original record unchanged, as happens if we edit a file in say NotePad, make some changes, and decide to create a new file. We SaveAs and continure editing. At the end, the original file is unchanged, and the new file has the changes from before the SaveAs and after it (presuming a final Save before closing).

Line #2 of the code suggested in Post #2 saves the record. If I select before any changes are made, it is un-selected when form becomes dirty.

I could save all the fields using each control's OldValue property. Then I select the record, allowing Access to save the changed record. On FormClose, I would have to move back to the original record, and restore the original values and save it. Procedures would have to be recursive, because I might want to create a series of records, each a slight change from the previous one.

1. Call form
2. Make changes, say txtField = Test 1
3. "Save As" to create a new record
4 Change the 1 to a 2, avoiding typing the word "Test" and any other common data fields
5. "Save As" to create a new record
6. ... Repeat as necessary

This seems clumsy, crude, and amaturish. Like most of my code, I'm afraid.
Apr 8 '09 #4
ADezii
8,834 Expert 8TB
@OldBirdman
I do have a solution that I based on the [FirstName] and [LastName] Fields of the Employees Form in the Northwind Sample Database. Make changes to the First and Last Name Fields, then execute the following code within the context of the Form, making sure to previously Declare the Globals. An exact Duplicate of the Record will be created then Appended. The Original Record will revert back to its Original State prior to the changes. I know it is a little convoluted, but for now, see if it will do until a better solution comes along. I tested it and it actually does work! (LOL)!
Expand|Select|Wrap|Line Numbers
  1. Dim strSQL As String
  2.  
  3. '*******************************************************************************************
  4. 'Store Original Values in Public Variables  Declared in a Standard Code Module
  5. glngEmployeeID = Me![EmployeeID]
  6. gstrFirstName = Me![FirstName].OldValue
  7. gstrLastName = Me![LastName].OldValue
  8. '*******************************************************************************************
  9.  
  10. '*******************************************************************************************
  11. 'Define the SQL Statement that will restore the Original Values to the very Record from which
  12. 'changes were made, and a Duplicate created
  13. strSQL = "UPDATE Employees SET Employees.FirstName = '" & gstrFirstName & "', " & _
  14.          "Employees.LastName = '" & gstrLastName & "' Where Employees.[EmployeeID] = " & _
  15.           glngEmployeeID
  16. '*******************************************************************************************
  17.  
  18. '*******************************************************************************************
  19. 'Duplicate the Record with modifications
  20. 'Select Current Record
  21. DoCmd.DoMenuItem acFormBar, acEditMenu, 8, , acMenuVer70
  22.  
  23. 'Copy Current Record
  24. DoCmd.DoMenuItem acFormBar, acEditMenu, 2, , acMenuVer70
  25.  
  26. 'Paste Append Record
  27. DoCmd.DoMenuItem acFormBar, acEditMenu, 5, , acMenuVer70
  28. '*******************************************************************************************
  29.  
  30. '*******************************************************************************************
  31. 'Restore Original Values to the Original Record
  32. CurrentDb.Execute strSQL, dbFailOnError
  33. '*******************************************************************************************
  34.  
  35. 'P.S. - At some point you 'MUST' Reset the Public Variables before duplicating this Procedure
Apr 8 '09 #5
OldBirdman
675 512MB
OK, Good. I never used an UPDATE query pefore, so that was my missing piece. I don't get the Global Variables. Why? strSQL = "UPDATE ..." & Me![EmployeeID].OldValue & "..." & Me![FirstName].OldValue & ..... saves the data locally. It only has to last from line 13 to line 32.

Thank you for your time & effort.
Apr 8 '09 #6
ADezii
8,834 Expert 8TB
@OldBirdman
Anytime, sorry for the confusion, strSQL can be Declared Locally as is.
Apr 8 '09 #7
OldBirdman
675 512MB
This doesn't work, and I'm going nuts trying to figure why.

I have 2 tables, linked in Relationships. I'm trying to create a simple form to edit 2 of the fields in the child table, and be able to start an edit and then do a "Save As".

Expand|Select|Wrap|Line Numbers
  1. Tables
  2. Table 1 Name = tPhotographers
  3. Key as Autonum (Random) = PK
  4. ...
  5.  
  6. Table 2 Name = tPhotographerLocations
  7. Key as Autonum (Random) = PK
  8. Photographers  as Long 'Points to Key in table = tPhotographers
  9. LastDate       as Date
  10. Type           as String
  11. Location       as String
The form has 5 textboxes for the 5 fields in the table, named txtXXX where XXX is the name in the table. For testing, this form is being opened from the DataBase (Forms) window, and no other forms are open.

Expand|Select|Wrap|Line Numbers
  1. Private Sub Form_Load()
  2. 'Photographers key = 782320442
  3.     Me.RecordSource = "SELECT * FROM tPhotographerLocation WHERE Key=1251495069"
  4. End Sub 'Form_Load
  5.  
I have 1 record (Key=1251495069) a test record with Photographers pointing to a test record. Everything displays correctly at this point.

In txtLocation, I change the current value "Test 1" to my new value "Test 2". I press button = cmdSaveAs to create a new record, and to restore the initial record to its original state ("Test 1").
Expand|Select|Wrap|Line Numbers
  1. Private Sub cmdSaveAs_Click()
  2. Dim strSQL As String
  3. Dim iiHoldPtr As Long
  4.  
  5.     iiHoldPtr = txtPhotographer
  6.     If Me.Dirty Then
  7.         'Build SQL to restore original record
  8.         strSQL = "UPDATE tPhotographerLocation " & _
  9.                 "SET Type='" & Nz(txtType.OldValue, txtType) & _
  10.                 "', Location='" & Nz(txtLocation.OldValue, txtLocation) & _
  11.                 "' WHERE Key=" & txtKey
  12.     Else
  13.         strSQL = ""
  14.     End If
  15.  
  16.     'Select the record now being edited
  17.     DoCmd.DoMenuItem acFormBar, acEditMenu, 8, , acMenuVer70
  18.     'Copy the Record
  19.     DoCmd.DoMenuItem acFormBar, acEditMenu, 2, , acMenuVer70
  20.     'Paste append record to create new record
  21.     DoCmd.DoMenuItem acFormBar, acEditMenu, 5, , acMenuVer70 'Paste Append
  22.     Me.Dirty = False 'Force Save for test purposes only
  23.     txtPhotographer = iiHoldPtr
  24.     Me.Dirty = False 'Force Save for test purposes only
  25.     'Restore original record (if necessary)
  26.     If strSQL <> "" Then CurrentDb.Execute strSQL, dbFailOnError
  27. End Sub
With a breakpoint at Line 22, I have the following in Immediate (window). First, I did a cntl+V to paste the clipboard into Immediate.
Expand|Select|Wrap|Line Numbers
  1. txtKey  txtPhotographer txtLastDate txtType txtLocation
  2. 1251495069  782320442   4/8/2009    X   Test 2
I then printed some controls and variables:
Expand|Select|Wrap|Line Numbers
  1. ?txtKey, txtPhotographer, txtLastDate, txtType, txtLocation
  2.  1976622305    0            Null          X             Test 2
  3.  
  4. ?me.Dirty 
  5. True
Note that the foreign key txtPhotographer is 0 and invalid as there is no key=0 in table=tPhotographers. The date field is Null, also invalid, but the other fields are correct.
Attempting to run Line 22 gets me
Expand|Select|Wrap|Line Numbers
  1. Run-time error '3201':  You cannot add or change a record because a related record is required in table 'tPhotographers'. 
which is because txtPhotographer is now 0 and invalid. If I skip Line 22, and run Line 23, Line 24 also works. I really don't want to do this, because now UnDo in not possible, but for now, OK.
Line 26 restores the original record, and closing the form leaves me with 2 records, but the date is null in the 2nd record.

If I now change txtLocation to "Test 3" and continue, more problems occur. So I need to understand why this part doesn't work, rather than just force it with more code like Line 23.
A real-life example would be if a photographer visits a city briefly, the location might be entered as txtLocation =
Expand|Select|Wrap|Line Numbers
  1. AnyCity, SomeState, Country
If he returns for a more extensive visit, he might want to edit this, adding local locations such as
Expand|Select|Wrap|Line Numbers
  1. Central Park, AnyCity, SomeState, Country
  2. Waterfront Park, AnyCity, SomeState, Country
  3. Courthouse Park, AnyCity, SomeState, Country
  4. Civic Center, AnyCity, SomeState, Country
  5. ...
  6.  
Line 21 is the code that is producing incorrect results. Something is very wrong with this approach. Giving up the office clipboard is an undesired side-effect of this method, but I could live with it if it is the only way. Can it be fixed?

It seems like the code might be:
Expand|Select|Wrap|Line Numbers
  1. rst = tPhotographerLocations
  2. rstclone = tPhotographerLocations.clone
  3. rstclone = set to current record
  4. rst = set to new record
  5. assign rst from rstclone
  6. rstclone.undo
Any ideas here?
Apr 9 '09 #8
ADezii
8,834 Expert 8TB
@OldBirdman
Can you send me a Copy of the Database if I give you my E-Mail Address in a Private Message?
Apr 9 '09 #9
OldBirdman
675 512MB
That presented was a tiny piece of a larger system, including linked tables. I'll see if I can isolate this into a test database, as the problem is fairly simple.

When I've sent my problems to others, they don't recreate on their machines. That implies that mine are corrupt, although I run two different versions of Office (2000 and 2002). Both machines, 2 versions of a program produce the same symptoms.

I am going to try to figure how to do this with direct manipulation of the tables, as I hinted at the end of my previous post.

Thank you for your effort and concern.
Apr 9 '09 #10
ADezii
8,834 Expert 8TB
@OldBirdman
Try giving this Logic, or a modification thereof, a try:
  1. Declare the following Global/Public Variables in a Standard Code Module:
    Expand|Select|Wrap|Line Numbers
    1. 'To avoid the problem of potential Null Values, all
    2. 'Variables were Declated as Variants
    3. Public gstrType As Variant
    4. Public gstrLocation As Variant
    5. Public glngKey As Long
    6. Public glngPhotographer As Long
    7. Public gdteLastDate As Variant
  2. Execute the following code within the context of your Form:
    Expand|Select|Wrap|Line Numbers
    1. Dim strSQL As String
    2. Dim MyDB As DAO.Database
    3. Dim rstTest As DAO.Recordset
    4.  
    5. Set MyDB = CurrentDb
    6. Set rstTest = MyDB.OpenRecordset("tPhotographerLocation", dbOpenDynaset, dbAppendOnly)
    7.  
    8. '*******************************************************************************************
    9. 'Store Original Values in Public Variables  Declared in a Standard Code Module
    10. gstrType = Me![txtType].OldValue
    11. gstrLocation = Me![txtLocation].OldValue
    12. glngKey = Me![txtKey]
    13. glngPhotographer = Me![txtPhotographer].OldValue
    14. gdteLastDate = Me![txtLastDate].OldValue
    15. '*******************************************************************************************
    16.  
    17. '*******************************************************************************************
    18. 'Duplicate the Record with modifications using DAO, avoiding DoMenuItem, and creating
    19. 'a Related Record
    20. With rstTest
    21.   .AddNew
    22.     ![Type] = Me![txtType]
    23.     ![Location] = Me![txtLocation]
    24.     ![ptrPhotographers] = Me![txtPhotographer]
    25.     ![LastDate] = Me![txtLastDate]
    26.   .Update
    27. End With
    28.  
    29. rstTest.Close
    30. Set rstTest = Nothing
    31.  
    32. '*******************************************************************************************
    33.  
    34. '*******************************************************************************************
    35. 'Restore Original Values to the Original Record
    36. Me![txtType] = gstrType
    37. Me![txtLocation] = gstrLocation
    38. Me![txtLastDate] = gdteLastDate
    39. '*******************************************************************************************
    40.  
    41. '*******************************************************************************************
    42. 'Clear all Public/Global Variables
    43. gstrType = Null
    44. gstrLocation = Null
    45. glngKey = 0
    46. glngPhotographer = 0
    47. gdteLastDate = Null
    48. '*******************************************************************************************
    49.  
    50. Me.Requery
  3. Let me know how you make out.
Apr 11 '09 #11
NeoPa
32,556 Expert Mod 16PB
Without wishing to interrupt what is already a fairly involved conversation, have you considered using the Default attribute of the controls on the form you want to use to save the record away from?

There are techniques that can make this process less laborious (For Each Control etc). Let me know if this is an approach you would consider using.
Apr 16 '09 #12
OldBirdman
675 512MB
The problem is to open a form to edit a row of a table. During changing the fields, using this form, I may:
1) Save the changes - Automatic at form close, or command button. Easy
2) Undo the changes - Command button or ESC Key. Easy "DoCmd.UnDo"
3) Move the changes to a new record, restore original record, and continue where 1,2,3 are again possibilities. I'll look at any ideas here.
Apr 16 '09 #13
NeoPa
32,556 Expert Mod 16PB
Well, I don't see much benefit in progressing with this unless you feel it's a viable solution. I know you're always open to any suggestions, but if this doesn't look like a decent solution, I won't push it.
Apr 16 '09 #14
OldBirdman
675 512MB
ADezii has supplied such a solution to me personally, but I need more time to grasp all the implications. As I actually have 3 different places this would be useful, I will be trying to write a function that will work in the general case. Leave it alone for now, and I will repost in this thread when I know more.
Apr 16 '09 #15
FishVal
2,653 Expert 2GB
Some code to illustrate suggestions made by ADezii and NeoPa.

Expand|Select|Wrap|Line Numbers
  1. '[keyID] is PK, Autonumber field in the form recordsource
  2.  
  3. Private Sub btn_Click()
  4.  
  5.     Dim rs As DAO.Recordset
  6.     Dim lngID As Long
  7.  
  8.     'get an unbound copy of the form recordset
  9.     Set rs = Me.RecordsetClone
  10.  
  11.     With rs
  12.  
  13.         .AddNew
  14.  
  15.         'skip possible errors related to unbound or not updateable form controls
  16.         'and read-only recordset fields
  17.         On Error Resume Next
  18.         For Each ctrl In Me.Controls
  19.             'copy control value to recordset field the control is bound to
  20.             'IsNull() check is used since silly DAO.Recordset allows to modify Autonumber field
  21.             If IsNull(.Fields(ctrl.ControlSource)) Then .Fields(ctrl.ControlSource) = ctrl.Value
  22.         Next
  23.         On Error GoTo 0
  24.  
  25.         'remember PK of created record
  26.         lngID = !keyID
  27.  
  28.         .Update
  29.         .Close
  30.  
  31.     End With
  32.  
  33.     Set rs = Nothing
  34.  
  35.     With Me
  36.         'undo changes to the current record
  37.         .Undo
  38.         'form requery
  39.         .Requery
  40.         'go to the record created above
  41.         .Recordset.FindFirst "keyID=" & lngID
  42.     End With
  43.  
  44. End Sub
  45.  
Apr 16 '09 #16
ADezii
8,834 Expert 8TB
Nice Hybrid approach, FishVal.
Apr 18 '09 #17

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Phil Powell | last post by:
create table if not exists nnet_produkt_varegruppe ( nnet_produkt_varegruppe_id int not null auto_increment, primary key(nnet_produkt_varegruppe_id), nnet_produkt_varegruppe_navn varchar(255) not...
6
by: dev | last post by:
how create a temp table as a copy of a existing table and then update1 field and insert the hole temp table back in the existing table? please any help? if i have 10 fields in 1 record and...
4
by: Michael Jackson | last post by:
I have a stored procedure to create a table. In my program I want the user to name the table to be created, therefore I pass a parameter to the SP for the table name. I cannot get it to work. It...
7
by: Wolfgang Kreuzer | last post by:
Hello all, I have two tables - Projects and ProjectStruct Table Projects contains master records of the projects, ProjectStruct allows to define a project herarchie and contains the fields...
1
by: poohnie08 | last post by:
i have a excel spreadsheet showing staff name, date,work hour, ot hour, slot1, slot2, slot3, slot4 and others). The "()" will keep repeating from day 1 until end of month. eg in excel spreadsheet,...
24
by: flkeyman | last post by:
Work in legal office. Trying to create solid designed database structure. This is list of tables w/fields and primary keys. Any comments/advice greatly appreciated. tbl-Defendants CaseNumber...
6
by: Peter Nurse | last post by:
For reasons that are not relevant (though I explain them below *), I want, for all my users whatever privelige level, an SP which creates and inserts into a temporary table and then another SP...
27
by: max | last post by:
Hello, I am a newbye, and I'm trying to write a simple application. I have five tables with three columns; all tables are identical; I need to change some data in the first table and let VB...
4
by: etuncer | last post by:
Hello All, I have Access 2003, and am trying to build a database for my small company. I want to be able to create a word document based on the data entered through a form. the real question is...
2
by: lakuma | last post by:
Hi, I have a table called A (say) with columns called name, place, animal and thing. I would want to write an on insert trigger on this table, which would create a table with the name of the...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.