I'm trying to set up a simple form in MS access to add a new record to a table full of contact information. Each time I add a new record using the form, I want an ID number field to increment by one against whatever the highest value in the ID field is. The code I have right now seems to be working:
Private Sub Contact_ID_Click()
Dim newContactID As Double
newContactID = DMax("[Contact_ID]", "Contacts") + 1
Contact_ID = newContactID
End Sub
The problem is that every time I start the database, open up the form in form view and click on the Contact_ID field to increment it, I get the following error message:
"The expression On Click you entered as the event property setting produced the following error: Object or class does not support the set of events."
I go to design view, open up the code, and then as soon as I switch back to Form view it's working again. I'd like it to work when the form is opened from scratch as others might be using this form and wouldn't know what to do. Any idea what's causing this?
Related
I used the following VBA Code in The Form (General)
Public Function GetUserName() As String
GetUserName = CreateObject("WScript.Network").UserName
End Function
The Control source = User_Name
Default Value = GetUserName()
The Problem -
The username is correctly Pulled in the form, however it is not being saved in the Control Source i.e in the Table. Even after I save and close the form.
I need the form to capture and save the Username every time someone makes changes to a record.
Please Help I am new to MS Access
It looks like you are assigning the user name to the control source. Access does not work like this. The control source is supposed to contain a column name.
Create a table having columns you can use to store things. Then set the form's Record Source property to this table name at design time in the properties window. Then set the Control Source of a text box to the column name where you want to store data or add objects to the form using the fields list.
Iin the form load event you can assign a user name to this textbox with
me!theTextBoxName = GetUserName()
You can also do this with an unbound textbox, but this name will not be stored when you close the form.
But as #June7 points out, you have probably done this already. In this case you should open the form with
DoCmd.OpenForm "theFormName", DataMode:=acFormAdd
... to create a new record.
I am trying to write a value to a record as soon as it is pulled into the form in Access. I put the code into the Form_current event code, thinking this would work, but I am getting an unexpected result. It is writing to the previous record. So for example if I go from record A to record B, it will write the values to the fields in record A. Oddly, if I have a message box display the value of the field it will display the value from record B, though. It is very simple code, but here is what I have. I tried the RefreshRecord and DoEvents, because i thought they might help, but they did not.
Private Sub Form_Current()
Dim username As String
username = Right(Environ("USERPROFILE"), Len(Environ("USERPROFILE")) - InStrRev(Environ("USERPROFILE"), "\")) 'Removes path and keeps the Novell ID
DoCmd.RefreshRecord
DoEvents
Me.Record_lock = vbTrue
Me.Locked_by = username
End Sub
Any help on this would be appreciated. I have worked with VBA before in Excel, but never really in Access
Form_Current can fire repeatedly while the form is open ... not just once when the form is first opened.
From the Form.Current Event help topic ...
Occurs when the focus moves to a record, making it the current record,
or when the form is refreshed or requeried.
So with your code, it's not surprising that you have updated Record_lock and Locked_by values for record A after you navigate away from record A to record B.
At that point, record B has become the "current record", so it should have those updated values, too. You confirmed that point with MsgBox. However, the changes to that record may not have yet been saved, which means you would not see them in the source table yet.
If the remaining issue is that you're not seeing the updated record B values displayed in the form, add Me.Refresh on a separate line before End Sub.
I would like to comment first, but I am a new user. Have you tried refreshing the record, before modifying the field?
I am completely new to VBA. I have been told to add records to a table by using a form and a Save button and given some very basic instructions. While I have achieved this with inline query, I have been told to follow some strict methods like usage of QueryDef/QueryDefs and .Parameters.
So far I am trying a very basic project, just to grasp the concepts, but I am unable to add any record to an empty table. In case the table is not empty(I manually enter a record), whenever I click the Save button for saving newer records, the number of records added are somehow doubling with each instance. For example, when I Save for the 1st time, 1 record is added, 2nd time 2 records of the same type is added, 3rd time 4 are added and so on.
The table(tbl_test) has 2 fields --> ID(primary key), Source(Long Text) and Reg No (Number).
The query(qry_test) is made with the Append feature and I have been told to add expressions which makes the code like this -
INSERT INTO tbl_test ( Source, [Reg No] )
SELECT [strSource] AS Expr1, [lngRegNo] AS Expr2
FROM tbl_test;
The form has 2 fields for Source(txt_Source) and Reg No(txt_RegNo) which have blank Record Sources (Unbound). The Save button has the following Event Procedure -
Private Sub btn_save_Click()
Dim qdf As QueryDef
Set qdf = CurrentDb.QueryDefs("qry_test")
qdf.Parameters("strSource") = Me.txt_Source
qdf.Parameters("lngRegNo") = Me.txt_RegNo
qdf.Execute
End Sub
I have zero knowledge about VBA and would gladly accept ANY help. It would be great if I get any sort of source code that will explain to all the details about saving records from forms and editing them using these querydef, parameter and recordset stuff.
Welcome to StackOverflow!
If you are using a form to collect data for records that are stored in a table, running a saved append query by QueryDefs to do this is, in my opinion, not the best method.
Whilst an append query does add new records to an existing table, I would tend to use an append query where I've got multiple established records that I want to add to an existing table.
If I'm setting up a data entry form that is designed to collect new data for new records 1-at-a-time, an append query doesn't really suit this purpose.
Instead, there are a number of features built in to the design of MS-Access forms to help collect data and save it to a table. This is because forms are very much intended to be set up so that users can interact with records from a table in a controlled, user-friendly way rather than interact directly with the table object itself.
The first and most important feature of a form in this context is probably the form's record source property. When you create a new form, go in to design view for the form and open the form's property sheet (F4 key). In the "Data" tab of the form's property sheet you'll find the record source property:
The record source essentially connects your form with a set of records, whether those be records in a table object, a query object or an sql query string.
In your case it would be better, in my opinion, to bind your tbl_Test table to your form by referring to it in your form's record source:
It will seem like nothing has happened to your form, but if you now open the "Add Existing Fields" panel (alt + F8), you'll notice that the fields associated with your tbl_Test table are available to you:
Drag them to the detail section of your form...
Then put your form in to Form View:
Essentially what you and your users are seeing is the first blank record in your tbl_Test, but displayed on a form instead.
Entering data in these fields on the form...
...will put that data in to the table we specified in the form's record source...
So hopefully you can see that setting the form's record source property to that of your table, is much cleaner than trying to get an append query to collect data from your form and deliver it your table.
At this point you're probably asking a few questions:
When I have filled in the fields for a record on my form, how do I save that record?
More can be said about this, but for brevity, I'd recommend using a command button for running some vba to save the record; similar to what you've done, but utilising the form's Dirty property instead using an append query:
Here's the click event VBA for my save button example:
Private Sub cmdSave_Click()
If Me.Dirty Then
Me.Dirty = False
End If
End Sub
Me.Dirty is a Boolean (True or False) setting for the form; essentially it is automatically set to True when a user changes something on the form. To save those changes, the Me.Dirty setting will have to be set to False.
Me.Dirty is a bit like the swing gate on a sheep pen. When a shepherd puts a sheep (data) in the pen (form) they will open the gate to the pen. The open gate is like the form's Me.Dirty being set to True. To lock the sheep (data) in, the gate needs to be closed, or in the case of forms, the Me.Dirty property needs to be set to False. The VBA above essentially checks to see if the gate was opened and if it was to close it.
How do I move to a new record in the form once I have saved the current one?
Again, I'd give the user a command button to do this and run some VBA on its click event:
Here's the VBA for moving to a new record:
Private Sub cmdNew_Click()
DoCmd.GoToRecord , , acNewRec
End Sub
Summary
There is a lot more to consider than what I've outlined here, such as:
validating data before it is saved
checking other form events (such as close) to ensure data entry is not lost
navigating to an existing record
But hopefully what I've given you here is at least pointing you in a better direction. Best of luck!
Access is optimized for bound forms. Unbound forms are for special cases only.
Should you prefer unbound forms (could be for many reasons), Access isn't worth the trouble, and you should turn to Visual Studio and WinForms.
In either case, browse for a beginner's tutorial.
If you want to use an unbound for or unbound controls you can create the SQL string in the procedure:
Dim mysql as String
mysql = "INSERT INTO tbl_test ( [source], [reg_No]) VALUES (Me.txt_Source, Me.txt_RegNo)
DoCmd.RunSQL mysql
So in MS Access 2010 I have a main form for viewing client details, and tabbed subform navigation with subforms showing information in different tables for said client. On one page, i have a combobox to select a date for viewing a testing session related to the client. I am trying to get the first combobox value to be selected automatically when the user goes to this tab and/or cycles through other users while viewing this tab. My simple VB code is below:
Private Sub Form_Current()
Me.DateOfScreening.Requery
Me.DateOfScreening.Selected(2) = True
End Sub
The requery command is executing (paging through different clients will update the combobox values, and commenting that line out stops that behavior, so I know this code block is getting executed), but the Selected command appears to not select anything.
I hope I am just missing something obvious
For some reason, setting the selected row index for a combo box has not behaved well for me.
Could you just set the combobox value directly, as in
Me.DateOfScreening = "yourValue"
Also, when referencing the control, you can use either
me.dateofScreening.column(0) 'if 0 is your bound col index
or maybe
me.dateofScreening.itemdata(0)
Also, could you do a debug.print(me.dateofScreening.column(0)) or msgbox (me.dateofScreening.column(0)) and let me know if it says anything.
I use a subform to show the result of a query, but at the end of record there is a *(New) for adding new records. I don't want the user to be able to add new records through this subform. How can I get rid of this?
With the subform in Design View, open its property sheet. Then select the Data tab on the property sheet, find the property named "Allow Additions" and set it to No.
The "Allow Additions" property will not display if you open the design view of the parent form and click on the subform. The subform must be opened in Design View independent of the parent form.
Had exactly the same problem.
My DB is to keep track of basketball box scores. Every new main form created a new blank subform to enter the quarter scores into. The problem was as I Entered through the fields once I hit enter on the last quarter score value a new record was created for the table that Quarter Scores was based on.
I could not use Allow Additions = no. If I did not allow additions there was no quarter score input created when a new main form (for a new game) was created.
I used the code below for a key down event of the Enter key to set the focus on another subform before a new quarter score record was created.The commented lines were to help trouble shoot when creating the code. Key code 13 is the Enter key.
Hope this helps someone, took a while to get this right.
Den
Private Sub HOT2_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode <> 13 Then Exit Sub
'MsgBox "Enter Pressed"
KeyCode = 0
'MsgBox "KeyCode=0"
Forms!FRM_BoxScores.Scrimmage.SetFocus
Forms!FRM_BoxScores!subform_qryReturnVisitingPlayers_BosScores.Form!subform_tblPlayerPoints_BoxScores.Form!PlayerPoints.SetFocus
End Sub
Change Record-set Type to Screenshot in Data Form Properties > Data Tab. Please note user cannot change any Data in form you once you change this
in your subform design grid, open the properties.
Where is says recordset type, set it to snapshot. That will remove that line.
The recordset will NOT be updateable at that time. So if you want to edit records, you have to change it back