using vba to count buttonclicks on a userform - vba

Need help using vba to count button clicks. any suggestions???
couner = counter+1
this is what i found.
"The form does not necessarily have to have any link to the Audit Table, use a recordset to update the counter value. Use the DLookup function to find out the value in the Table ie
DLookup "[Counter]","Audit"
A progression from this would be to have an AuditTable with [Autonumber] and [ButtonName]. In this way you could count several ButtonClicks but give each button in your Db a separate name so to count these
DCount "[AutoNumber","AuditTable","[ButtonName] = 'NameOfButtonToCount'" You can then put this alongside the button in a visible or hidden field."
Actually this is for an excel doc. I have to submit a spreadsheet for pc printer mapping to another group to process. the purpose of counting clicks is to help tell the program to go to the next row in excel. I add anywhere between 1-15 pcs to one spreadsheet and just trying to automate the process.

Going to assume you want some sort of audit log for actions taken using buttons on an Access form. Without knowing anything else all I can do is try to point you in the right direction. If you're trying to see who is doing what and when in your database then you can create an AuditTable with fields: Form, Button, Timestamp, User, Computer. Whenever the user clicks a button, executes a SQL statement to update the audit table:
Dim SQL As String
SQL = "INSERT INTO " & _
"AuditTable " & _
"(Form, Button, Timestamp, User, Computer)" & _
"VALUES" & _
"('" & Me.Name & "','" & YOUR_BUTTON_NAME_HERE & "',#" & Now & "#, '" & Environ$("username") & "','" & Environ$("computername") & "');"
CurrentDb.Execute SQL
If you want to count your button clicks you can then: SELECT Button, count(1) as Clicks FROM AuditTable GROUP BY Button

Related

Microsoft Access - Using a form to input data into a different table with VBA?

Trying to use a form named 'Customer Entry', that when clicked, enters the data that has been typed in said form into a table that is named 'CustomerRecord'. I keep getting errors and am at my wits end. Here is my code below, this is in VBA.
Public Sub Command19_Click()
CurrentDb.Execute "INSERT INTO CustomerRecord(Customer Name, APM, UAID, Context Code, Purpose Code, Context Description, Purpose Description) " & _
" VALUES (" & Me.txtCustomer Name & ", " & Me.txtAPM & ", " & Me.txtUAID & ", " & Me.txtContextCode & "," & Me.txtPurposeCode & ", " & Me.txtContext Description & ", " & Me.txtPurpose Description & ")"
frmCustomer
Entry.Form.Requery
End Sub
If you want to edit data from two tables on a single form you need to make an updatable query to base your form upon. Set your forms RecordSource property to be the updatable query. Now you can add form elements from the source that allow the user to edit all the fields directly.
See this list of pitfalls to ensure that your query is updatable:
http://allenbrowne.com/ser-61.html
If you absolutely must edit data elsewhere from your form, which you occasionally must do, don't use an SQL query execute statement to do so. Use a recordset object instead. This is both more secure, more reliable, and easier to read the code.
See this guide for an example of how it's done: https://learn.microsoft.com/en-us/office/vba/access/Concepts/Data-Access-Objects/modify-an-existing-record-in-a-dao-recordset
Additional reading: https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/recordset-edit-method-dao

Locate a TempVar in a MS Access main form and write it to a table connected to the subform

I need to add some VBA code to a checkbox located on a subform of my front end Access 2016 database.
The goal is to insert to a table the value contained in a textbox located in the main form.
So far, the steps I took are:
Click on the checkbox located on the subform;
Create a temporary variable;
Insert the temporary variable into the related table;
Move on to the next item.
The code is the following:
Option Compare Database
Private Sub AssegnatoCampione_Click()
'Create temporary variable and store the selected value
TempVars("NumeroCampione").Value = Forms!FormCampioni2.SampleNo.Value
'Write the value in the database
CurrentDb.Execute " INSERT INTO DB_Offerte2017 " _
& "([NumeroCampione]) VALUES " _
& "(" & TempVars![NumeroCampione] & ")" ', dbFailOnError
End Sub
The error I get is: .
"Too few parameters. Expected 1."
Is there a way to know whether the variable is stored correctly or not?
Thank you so much for your help.
Edit 1:
Ok, so i guess that the error was due to DB_Offerte2017([NumeroCampione]) being a text field. I corrected the code in this way:
CurrentDb.Execute "INSERT INTO DB_Offerte2017 ( NumeroCampione ) VALUES ('" & Me.Parent.SampleNo & "')", dbFailOnError
This way, every time I click on the check box, a new record is added in the table "DB_Offerte2017", under the field "NumeroCampione".
However, I need to add those records to the same row where the checkboxes is located (e.g. Click on checkbox where ID = 2438 -> Add "SampleNo" value on DB_Offerte2017.NumeroCampione where ID = 2438).
Is it possible to add a where statement in the code?
Why not just a normal VBA variable or just reference the control? Code is behind subform and field/control on main form? Try:
CurrentDb.Execute "INSERT INTO DB_Offerte2017([NumeroCampione]) VALUES (" & Me.Parent.SampleNo & ")", dbFailOnError.

Microsoft Access 2010 - Dynamic query

I have an access web database that several users will need to log in to. The database contains a table of products.
The challenge is, every user needs to only see a subset of these products and never see the whole list.
At the moment i have some code to modify an existing query based on the logged in user's details. As they log in, some tempvars are created and these are used to modify the query criteria.
This works well when the first user logs in, but the moment the next user logs in, the query is modified again and the product list refreshes and now his products are shown and not the first users! Im thinking i need to dynamically create a permanent query for each user on log in?
Or is a better way to accomplish what im trying ? im quite new to access and struggling. Can anyone assist please?
Here is my code so far:
Button on login form has the following code that collects the user's details
Private Sub cmdLoginMine_Click()
Dim ID as long, strEmpName as string,strZondsc as string,strgrpdsc as string
ID = DLookup("ID", "Employees", "Login='" & Me.txtUser.Value & "'")
strEmpName = DLookup("FullName", "Employees", "Login='" & Me.txtUser.Value & "'")
strgrpdsc = DLookup("MyGrpdscs", "Employees", "Login='" & Me.txtUser.Value & "'")
strzondsc = DLookup("MyZondscs", "Employees", "Login='" & Me.txtUser.Value & "'")
TempVars.Add "tmpEmployeeID", ID
TempVars.Add "tmpEmployeeName", txtUser.Value
I then call a function that modifies the existing query, populating it with this users details for the criteria
qryEdit strgrpdsc, strzondsc, ID
Sub qryEdit(strgrpdsc As String, strzondsc As String, ID As Long)
Dim qdf As DAO.QueryDef
Dim qdfOLD As String
Set qdf = CurrentDb.QueryDefs("InventoryQryforDS")
With qdf
.SQL = "SELECT Products.ProductCode, Products.ProductName, Products.GRPDSC, Categories.Category, Inventory.Available " & _
"FROM (Categories INNER JOIN Products ON Categories.ID = Products.CategoryID) INNER JOIN Inventory ON Products.ID = Inventory.ProductID " & _
"WHERE Products.GRPDSC in (" & strgrpdsc & ") and Categories.Category in (" & strzondsc & ") and products.ownersid =" & ID & _
" ORDER BY Products.ProductCode"
End With
Set qdf = Nothing
End Sub
The results of the query are shown on a form, which is what is currently requerying and showing the wrong data.
Thanks
EDIT - THe data is shown on a form, linked to one of the new style navigation buttons as shown.The recordsource property of the form is the query that's populated as described above.
I have a few suggestions/corrections to your approach to solving this issue.
When using DLookup, make sure they are enclosed within Nz() function, if the value you are looking for is not found you might be facing troubles of assigning a Null value to a Data Type that cannot handle Null. Anything other than Variant type will suffer.
You seem to do not one but four DLookup's on the table. This could be very expensive. This could be minimized by using a simple RecordSet Object.
I would not use TempVars much as they could be tricky to understand and implement.
Why are you editing the Query? This could again be a bit expensive in terms of memory. How are you showing the list of Products? In DataSheet or ComboBox or LsitBox? You could yet again change the RecordSource or RowSource of the Objects rather than editing the Query itself.
Finally, your users should all have a separate copy of the Front End file. Not one copy used by 20-30 people. If the files is restricted to be used by one person, then the code should work regardless of being modified. As the user will have access to the right data at all times.

How to do a MS Access Update query for a table in external database

Im trying to perform an update query on a table that its on a separate database, so far i have this SQL:
UPDATE [;database=C:\QA_Daily_YTD_Report_Export.accdb].[YTD-Daily_Report] AS EXT_DB
SET EXT_DB.Category1 = "1"
WHERE (EXT_DB.Category1 = "status1");
When i run this it returns an "invalid operation" error. Any idea what im doing wrong?
I would recommend linking the table [YTD-Daily_Report] into your database because you can easily put the update query into your code without having your code execute the connection to the other database.
You can link a table in Access by clicking on the External Data. Then click on the Access symbol.
You should then get a dialog box like this:
Be sure you choose the second radio button because you don't want to import the data from the database, just link it.
Navigate to the location of the Database and click on it. Then make sure your database is shown in the dialog box above and click okay.
You should then get a dialog box like this one that will show the table you won't. Highlight it and click okay. Now you can rename the linked table with any name you want and this will be a much less of a stumbling block for your work.
Try to omit ;database=
UPDATE [C:\QA_Daily_YTD_Report_Export.accdb].[YTD-Daily_Report] AS EXT_DB SET EXT_DB.Category1 = "1" WHERE (EXT_DB.Category1 = "status1");
I ended up using VBA in a form, just in case someone is wondering how here it is:
Dim SQL As String
Dim db_external As Database
Set db_external = OpenDatabase(CurrentProject.Path & "\QA_Daily_YTD_Report_Export.accdb")
SQL = "UPDATE [YTD-Daily_Report]" & Chr(13) & _
"SET [YTD-Daily_Report].Category1 = '" & New_value & "'" & Chr(13) & _
"WHERE ([YTD-Daily_Report].Category1= '" & Look_up_value & "');"
db_external.Execute SQL

Run form-based code multiple times using vba

Currently have a database containing the location of devices, and a form used to update the location of the devices and save a copy of their previous location. Ideally want to be able to input a list of "BoxNo" values (the ID field) and run the form multiple times with the same update on each record. Is this possible with VBA/SQL? Very low level of programming knowledge, any help would be much appreciated.
EDIT: As requested by Gord Thompson, clarification on the form procedure.
On the form there is a boxnumber textbox, which is locked and changed only by using the search bar at the bottom of the page i.e in the navigation pane part, not the form itself, and a few text and comboboxes which correspond to fields related to the boxnumber. The user changes the relevant fields and then clicks an "update" button which runs the following code (The part relevant to the question is after the else statement).
Private Sub Update_Click()
'checks whether date updated
If DateUpdated = False Then
MsgBox "Please enter a date", vbOKOnly, "Enter Date"
'saves copy to "changes" table
Else
DoCmd.SetWarnings False
DoCmd.RunSQL "INSERT INTO Change_In_Location_tbl (Sm_ID,Given_To,On_Date, Comments) VALUES ( " & Sm_ID.OldValue & ",'" & Currently_Held_by.OldValue & "','" & Date_Given.OldValue & "','" & Comments.OldValue & "');"
DoCmd.SetWarnings True
MsgBox "Update Complete", vbOKOnly
End If
End Sub
Sounds like you want to use a Do While loop. Assuming you have the list of values in a table, open the recordset and loop through each value.
Dim db as Database
Dim rec as Recordset
set db = CurrentDB
set rec = db.OpenRecordSet ("Select * from MyTableWithBoxNoValues")
Do while rec.EOF = False
... process the BoxNo and save it
(i.e., whatever your form is currently doing...)
rec.MoveNext
Loop