473,395 Members | 1,343 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,395 software developers and data experts.

How to edit an existing record instead of adding a new one using VBA?

beacon
579 512MB
Hi everybody,

[Access 2003]

On the surface, I thought my question would be an easy one to resolve, but it's turned out to be more challenging than I expected...or, I'm sleep deprived and just not thinking clearly.

Anyway, I've got a subform [sfrmDataCollection] in a main form [frmStandards] that are linked using [ID] as the master and [StandardsIDFK] as the child. The primary key for the query that [sfrmDataCollection] is based on is [DataCollectionID].

The subform is set to datasheet view and I've hidden the [DataCollectionID] and [StandardsIDFK] fields. The user has to enter values in the [CollectionYear], [Score], [CollectedBy], and [DataSource] fields.

I'm trying to add logic that will only allow the user to enter one record for a given year. So, if the user enters a collection year of 2011 in the first record, they can't enter 2011 again for that subset of the master [ID] field.

However, I want the user to be able to edit the record for 2011 and update the data. I've been able to successfully allow the user to edit a record, but it's not preventing the user from enter another record with the same year.

So, if the subform has collection year 2011 for the first row in the datasheet, the user can edit this information successfully and have it applied to the same row in the underlying table/query. However, if the user adds a new record at the bottom of the datasheet, they can enter 2011...the form will display a prompt asking the user if they want to edit the found year, but if the user says yes and adds info in the other fields, it creates a new record in the underlying table/query instead of updating.

Here's the code I've been working with so far:
Expand|Select|Wrap|Line Numbers
  1. Private Sub Form_BeforeUpdate(Cancel As Integer)
  2.  
  3.     Dim db As DAO.Database
  4.     Dim qdfDataCollection As DAO.QueryDef
  5.     Dim rsCurrentYear As DAO.Recordset
  6.     Dim strSQL As String
  7.     Dim dataExists As String
  8.     Dim userselection As Integer
  9.     Dim varStandard, varCollectionYear, varWhere, varStandardOld, varCollectionYearOld, varScoreOld, varCollectedByOld, varDataSourceOld, varCommentsOld
  10.  
  11.     varStandard = Null
  12.     varCollectionYear = Null
  13.  
  14.     'Strings to notify the user about
  15.     'the status of the collection year
  16.     '------------------------------------
  17.     dataExists = "Data for " & Me.CollectionYear & " has already been collected for the standard you selected." + vbCrLf + vbCrLf + "Do you want to edit the data for " & Me.CollectionYear & "?"
  18.  
  19.     varStandard = Me.StandardsIDFK
  20.     varCollectionYear = Me.CollectionYear
  21.  
  22.     'Set the parameters string
  23.     '---------------------------
  24.     strSQL = "SELECT * FROM qryDataCollection WHERE " & _
  25.              "[StandardsIDFK] = " & varStandard & " AND [CollectionYear] = " & varCollectionYear
  26.  
  27.     'Open the recordset and move to the last
  28.     'record to determine the number of records
  29.     '-------------------------------------------
  30.     Set db = Access.Application.CurrentDb
  31.  
  32.     Set rsCurrentYear = db.OpenRecordset(strSQL)
  33.  
  34.     'Check that there are results and notify the user
  35.     '--------------------------------------------------
  36.     If Not rsCurrentYear.BOF And Not rsCurrentYear.EOF Then
  37.         rsCurrentYear.MoveLast
  38.         If rsCurrentYear.RecordCount = 1 Then
  39.             If rsCurrentYear!StandardsIDFK = varStandard And rsCurrentYear!CollectionYear = varCollectionYear Then
  40.                 varStandardOld = rsCurrentYear!StandardsIDFK
  41.                 varCollectionYearOld = rsCurrentYear!CollectionYear
  42.                 varScoreOld = rsCurrentYear!Score
  43.                 varCollectedByOld = rsCurrentYear!CollectedBy
  44.                 varDataSourceOld = rsCurrentYear!DataSource
  45.                 varCommentsOld = rsCurrentYear!Comments
  46.                 Beep
  47.                 userselection = MsgBox(dataExists, vbQuestion + vbYesNo, "Data Exists: Update/Cancel?")
  48.                 If userselection = vbNo Then
  49.                     Cancel = True
  50.                     Me.Undo
  51.                 End If
  52.             End If
  53.         ElseIf rsCurrentYear.RecordCount > 1 Then
  54.             MsgBox "An error occurred. There are multiple records in the database for " & Me.CollectionYear, vbExclamation + vbOKOnly, "Error: Multiple Collection Years"
  55.             Cancel = True
  56.             Me.Undo
  57.         End If
  58.     End If
  59.  
  60.     Set rsCurrentYear = Nothing
  61.     Set db = Nothing
  62.  
  63. End Sub
  64.  
Me and my tired brain appreciate the help! =)

Thanks,
beacon
Aug 16 '11 #1
5 4606
NeoPa
32,556 Expert Mod 16PB
You need to get your principle logic working better Beacon. Consider the following and see if it doesn't make the whole thing fall into place more naturally, and make designing the code far easier (BTW nice job on explaining the problem. I wish all problems were explained as clearly and succinctly.) :

Start with a form/subform setup very similar to what you currently have but with the following difference - There is now an unbound control (You can make it a ComboBox if you like but a simple TextBox would do fine.) on your subform (in the header or footer so that it appears only once for the form) for selecting a year.

Whenever the value of this control is updated some code runs to :
  1. Determine if the matching year record already exists.
  2. Select the correct record for that year (The New record if the record doesn't already exist).

The Form_Current() procedure would need to ensure no other method was used to navigate through the records.

The DefaultValue property of the [Year] control would be set when a new record was selected and either of its Enabled or Locked properties should be set to disallow the operator from ever changing it.
Aug 17 '11 #2
beacon
579 512MB
Hi NeoPa,

I left out one important detail, which may change things slightly, although I think a minor tweak to your suggestion would still work...please interject if I'm off base.

The main form actually has a tab control and the subform is on one of the tabs (there's actually a subform on three out of the four tabs, but the one I'm working with is on the last tab, the other two are good). So, when the form opens, the record is associated with a standard number and the first tab displays general info about the standard, while the next three tabs show different pieces of information.

The info on the last tab, where the sfrmDataCollection resides, contains info that may be added or edited, depending on the needs of the user. The requestor had asked that they be able to update the subform datasheet and have it determine if the record needs to be edited or if it needs to be added.

I think I could probably get away with your suggestion, but I'm wondering, since I'm using the tab control, if I really need to put an unbound combo/text box in the header/footer of the subform. It sounds like your suggestion will display nothing until the user selects a year and the requestor wants all records to remain visible in the datasheet for the sake of making quick comparisons for a given standard.

I was thinking that I should be able to add unbound controls immediately above the subform to allow the user to input info. Once the user has input his/her info, they could hit a command button that would use DAO to add/edit the underlying table/query, then requery the now locked subform to display the addition/change.

Then, I could use the Form_Current() event to clear the data in the input fields in case the user tried to navigate to a different standard before submitting the info for another standard.

Like I said above, main thing that the requestor is looking for on this tab is for the user to be able to see multiple years in the datasheet for a given standard for quick comparison. I don't think the user really cares if the info is updated directly in the subform, although it would be nice if it could without having to add any additional fields.

Does this make sense? Is what I've outlined above basically what you were suggesting and will the placement of unbound fields in the detail section, as opposed to the header/footer, cause problems?

Thanks again for the help,
beacon
Aug 17 '11 #3
NeoPa
32,556 Expert Mod 16PB
It doesn't sound like you've quite grasped this Beacon. At this point I'd suggest reading the post (#2) again carefully.

Now I'll just point out some things which hopefully, by now, won't come as a surprise :
  1. The suggestion doesn't stop any of the records of the subform from being displayed. It merely stops any being navigated to without using the new, unbound control in your header / footer section (or if on a Tab (or Page) then as a separate control on the tab, but not in the Detail section).
  2. The code in the Form_Current() procedure can actually be omitted if you prefer. If you want to allow the operator to navigate normally between existing data records on that subform. The [Year] control should still be locked / disabled if you want to ensure the operator never changes the year for an existing record, but they would need to use the unbound control to enter the year for a new one.

Obviously, you can deviate from the suggestion wherever you feel it suits your purposes, but I wouldn't add the unbound control to the Detail Section unless you want a copy of it for every record (which wouldn't fit the plan, as I've outlined it at least).

It does help to mention that you're working on a tab, but it shouldn't effect the concept too drastically. Let me know whether this new understanding makes more sense. remember though, most of what you want to do can be done easily enough. It's the proper logical determination of exactly what's required that's the hard bit (and in the case of working on a forum, writing that down clearly enough so it makes sense).
Aug 17 '11 #4
beacon
579 512MB
Just to clarify one part, which may be partly what was confusing me in your original reply...I wouldn't be able to put the unbound control in the header/footer of the subform since the subform is set to datasheet view, right? Or am I being completely dense and forgetting how to display the header/footer in datasheet view (I didn't think it was possible, but just wanted to check that there isn't some workaround)?

I've used continuous forms to mimic datasheet view before, but the subforms on the other tabs are set to datasheet view and I was really hoping a) that the subforms would use the same default view and b) I wouldn't have to re-do the default view on any of the subforms (this is my OCD/perfectionist side rearing it's ugly head)
Aug 18 '11 #5
NeoPa
32,556 Expert Mod 16PB
Datasheet view does indeed preclude the use of Headers/Footers. I was confusing that with Continuous Forms. My apologies. Nevertheless, the unbound control can still be maintained on the Page (Tab) instead. It just means references to it are a little more complicated.

Never apologise to me for being OCD/Perfectionist. Database developers particularly should see these attributes as a definite bonus.

Personally I never use Datasheet View, as I don't think it looks as good as you can get with form design, but consistency is definitely worth appreciating regardless. If Datasheet View works for you then I'm sure we can manage the concept around that (but as you say it certainly precludes seeing any Headers/Footers).
Aug 18 '11 #6

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

Similar topics

2
by: Mark Perona | last post by:
I created an ASP.net form with an editable datagrid on it. I can create new records, and update and delete existing records. The problem I have is that I want a field in the grid to be editible...
12
by: daniel | last post by:
Hi All, I have a form and VB code in Access. The code is like With rs .Edit !Field = 10 .Update End With
0
by: tone | last post by:
i have just changed a field so that it automatically grabs x/y coord for a site from an arcmap doc. problem is that as it does this it creates a new record for each site instead of updating the...
1
by: sonasiva | last post by:
Dear all Iam using ASP i need to edit a record i have 4data fields as follows name companyname date percentage First user have to enter "name ,comapanyname and date" in th form...
1
nev
by: nev | last post by:
Good day to all! I was trying to search the internet about this problem but I still can't seem to stumble upon an answer. I am using a BindingSource on my program and everything is ok except that...
1
by: gurmet | last post by:
Hi All I have been looking around for help, and finally post this problem. I created a form to edit a record. Before i can click save button on the edit form i need to check if the data that...
0
by: ghjk | last post by:
I'm new to java.I,m developing web application using jsp,struts,hibernet. I want to edit database record. This is my code and when I edit and save it it didn't update record but add a new one. Please...
11
by: prashantdixit | last post by:
Hi, I am developing a stock control software. Iam stuck somewhere. I have a form "Add new stock" consisting of combobox, text boxes etc. which is used to add records in a table. I have another...
0
by: lenniekuah | last post by:
Hullo Friends, I need your help. Please help me. While trying to verify an existing record in the SQL SERVER table using the user input on TextBox it generate this error message: Input string...
3
TheSmileyCoder
by: TheSmileyCoder | last post by:
Im using an imagecombo in my form, and I have its Text property set to "Please Select". The text property of the imagecombo is what is displayed when you have not yet made a selection, kinda like...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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: 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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
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
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.