Run a Query Using a Button in Access - sql

I am trying to run a query in Access 2010 inside of a form. The form, per user request, needs to have buttons that they can use to quickly change the data in their column. For the table being called, there are only two columns that matter: Equiptment_Name and Amount (The other several columns are just there to help reference the data in case they misspell the name of the product). The current query I have is:
UPDATE tblInventory SET Amount = Amount-[Enter Amount]
WHERE ((([tblInventory].Equiptment_Name)=[Enter Name]));
This works perfectly, I just can't get it to work in a form with a button. I've searched all over for help and was encouraged to use a macro because that would be the easiest way. Can someone please walk me through the process of getting a macro to run a version of my query? I'm fine with the user being prompted to enter the amount to withdraw from the Amount category, but it would be nice if they didn't have to type in the Equiptment_Name category since The button would be in the form next to it (see picture below). Thanks for all help in advance.

You could simply use VBA to get this going. Something along the lines of
Private Sub Command70_Click()
If Len(Me.AmountTextBoxName & vbNullString) = 0 Then
MsgBox "Amount cannot be empty !", vbCritical
Exit Sub
End If
If Len(Me.Equiptment_NameTextBoxName & vbNullString) = 0 Then
MsgBox "Equiptment Name cannot be empty !", vbCritical
Exit Sub
End If
CurrentDB.Exeucte "UPDATE tblInventory SET Amount = Amount - " & Me.AmountTextBoxName & _
"WHERE tblInventory.Equiptment_Name = '" & Me.Equiptment_NameTextBoxName & "';"
End Sub
I have taken the Equipment name is actually a String.

Related

Word VBA: Static Status dialog window

I've created a form that works well with macros running in the background to validate data and then print the document to a specific printer on the network.
The key element of this process is a production number value which I would like to keep a running log of and display in a static status dialog window. In other words, a popup window similar to a MsgBox that would not interfere with other actions on the form, but float on top of the document.
Visual concept of this would be...
User could shift the window away from their work if needed. Close the window if they desired, but pragmatically I want to re-pop/refresh the data in the window each time the background macro completes.
I can't use MsgBox, because it forces a closure of the window before the user can continue working on the document. I just want this visible to the user so they know what was last worked on and the few prior to that.
Any idea what control I might be able to use, or switch to MsgBox that would allow the user to continue working?
Ken...
PS: I found this and am trying to find a way to make this work for me. So far I have managed to get to function in the manner I want, but the lingering issue is how to call this PS script and include the information I need to display.
Alternatives to MsgBox in VBScript - StackOverflow
PPS: I opted to go a slightly different route and release the form with a MsgBox that is displayed at the end of the macro. I describe this in the solution noted below.
Instead of using a MsgBox, please consider using a VBA Userform. They're not much more complicated to use than a MegBox, but you can set them to be Modeless. Modeless dialogs remain open on-screen while you work on the Word document. Here'is Microsoft's page on setting dialogs as Modal or Modeless: Show method
If you search on VBA modeless dialog, you'll find many other helpful pages on the subject.
After doing much research, I've come back to revising my macro to incorporate static variables and a MsgBox at the end to report the last 5 production numbers that have been printed.
To provide a means of bringing up this MsgBox for reference, between printing runs, I created an OnlyNum variable as string and replaced the MsgBox I had for letting the users know they were only to use numbers in this field with that message. The end of that trap diverted the flow to the bottom of the macro (where the MsgBox that displayed the last five print jobs has been placed).
So, when the status MsgBox is displayed as a result of printing it only shows the last five events. If the trap captures it, it shows the message letting the user know to only use numerals and then displays the last five events.
Code reference:
Private Sub CommandButton1_Click()
Dim Prod As String
Dim Temp As String
Dim OnlyNum As String
Static ProdNum1 As String
Static ProdNum2 As String
Static ProdNum3 As String
Static ProdNum4 As String
Static ProdNum5 As String
'Check for only numeric value of TextBox1.Text
If Not IsNumeric(TextBox1.Value) Then
OnlyNum = "only numbers allowed" & vbCrLf & vbCrLf
Cancel = True
GoTo NotToday
End If
'Remove any spaces from TextBox1.Text
Prod = Replace(TextBox1.Text, " ", "")
'If the resulting lenght is equal to 7 Print it.
If Len(Prod) = 7 Then
ActiveDocument.PrintOut
'Update recent production numbers (5 in total)
ProdNum5 = ProdNum4
ProdNum4 = ProdNum3
ProdNum3 = ProdNum2
ProdNum2 = ProdNum1
ProdNum1 = Prod & " - " & Now() ' Insert a new production number with timestamp
TextBox1.Text = "" 'Clear the value of TextBox1.Text to prepare for the next Production number
Else
MsgBox ("Production Numbers must be 7 digits and contain only numerials.")
End If
NotToday:
Application.ActivePrinter = Temp
MsgBox (OnlyNum & ProdNum1 & vbCrLf & ProdNum2 & vbCrLf & ProdNum3 & vbCrLf & ProdNum4 & vbCrLf & ProdNum5)
OnlyNum = "" 'Reset value of OnlyNum
End Sub

How do I prevent duplicate entries in my Access database?

I am a first time coder with VBA and I am creating a database for data entry at a Psych Lab I work at. Currently the database is created, but I want to prevent duplicate entries from being put into the database (namely by have a code look for the participant number right after it is entered). I have been trying to fix this code for quite a while and I just recently hit a wall. It displays the correct error message when I enter the participant number, however it says that every number has been entered already (even though they actually haven't). Here is the code:
Private Sub Participant_Number_BeforeUpdate(Cancel As Integer)
Dim Participant_Number As Integer
Dim StLinkCriteria As Integer
If (Not IsNull(DLookup("[Participant_Number]", "Entry Log", "[Participant_Number] ='" & Me.Participant_Number.Value & "'"))) Then
MsgBox "Participant Number has already been entered in the database."
Cancel = True
Me.Participant_Number.Undo
End If
End Sub
Any help is greatly appreciated. I have never used VBA before and I am self-teaching how to code.
I guess your Participant_Number field is a number. You shouldn't enclose the criteria with single-quotes ', these are used with fields of text type. Try changing the criteria field from
"[Participant_Number] ='" & Me.Participant_Number.Value & "'"))) Then
into
"[Participant_Number] = " & Me.Participant_Number.Value))) Then
IF you have not used VBA you may try to do this by opening the table in Design view. This method is easy and a good choice. You may have a look here: https://support.office.com/en-us/article/Prevent-duplicate-values-in-a-field-b5eaace7-6161-4edc-bb90-39d1a1bc5576?ui=en-US&rs=en-US&ad=US&fromAR=1

How do you declare a FOR EACH loop in MS Access database relationships in VBA?

I have a database for tracking family passes and member usage at our pool. I have 3 tables, one for family details, one for every individual member, and one for tracking check-ins.
There's a relationship that connects each individual record is appropriate family pass. Each individual is issued a pass that is scanned by a barcode scanner and checks them in using a simple form, I want to write a loop for a button that will check in every member of the family when they show up together, instead of having each individual scan their card.
DoCmd.OpenForm "CheckIn"
Dim person As ?
Dim family As ?
FOR EACH person IN family
Forms!CheckIn![PASSHOLDER] = Me![BARCODE]
Forms!CheckIn![CHECKINTIME] = Now()
DoCmd.GoToRecord , , acNewRec
NEXT
DoCmd.Close acForm, "CheckIn", acSaveYes
Problem is I don't know enough about VBA to figure out how to accomplish this. Do I need to create an array first? How do I prepare my data from my relationships in order to execute my loop?
Assuming the normalized structure below between tables, simply use SQL. Recall forms are just visual representation of tables usually for data management (add, edit, save, delete). Since you know what to add, automate the data entry with backend querying.
Family Details
FamilyID ...
Individual Members
MemberID, FamilyID ...
CheckIns
MemberID, PASSHOLDER, CHECKINTIME ...
So in VBA, if a family checks in press the button and run an append query which after refresh will show as individual records in the CheckIn form. This assumes some Family identifier textbox resides on form to be used in WHERE clause and in this case make it an unbound textbox including bar code since these fields will not be used for user data entry but SQL-automated data entry. Even consider an unbound form apart from actual CheckIn for this particular automation.
Private Sub FamilyCheckinCommand_Click()
If Not IsNull(Forms!CheckIn![FamilyID]) Then
strSQL = "INSERT INTO CheckIn (MemberID, PASSHOLDER, CHECKINTIME)" _
& " SELECT m.MemberID,'" & Forms!CheckIn![BarCode] & "', Now()" _
& " FROM IndividualMembers m" _
& " WHERE m.FamilyID = " & Forms!CheckIn![FamilyID]
' RUNS QUERY
CurrentDb.Execute strSQL, dbFailOnError
' REFRESHES FORM
Me.Form.Requery
Else
Msgbox "Please enter a family!", vbExclamation, "MISSING FAMILY"
End If
End Sub
Can you try like this? It may work :) (without the rest of the code and not knowing what exactly is family it is hard to say):
DoCmd.OpenForm "CheckIn"
Dim person As variant
Dim family As variant
'you should assign person to something actually.
FOR EACH person IN family
Forms!CheckIn![PASSHOLDER] = Me![BARCODE]
Forms!CheckIn![CHECKINTIME] = Now()
DoCmd.GoToRecord , , acNewRec
NEXT
DoCmd.Close acForm, "CheckIn", acSaveYes
This is how you iterate over a collection:
https://msdn.microsoft.com/en-us/library/y0e76axa(v=vs.100).aspx

Create query to take select data from multiple other tables on command button click

I am going to try to make this question as detailed as possible as it's a really confusing one, at least in my mind. First of all lets start with what everything is called. There are 2 forms, 1 button, 4 tables, and 1 temp-query.
The 2 forms are called WorkOrderDatabaseF & WorkOrderInfoF.
The button is called WorkOrderMoreInfoButton, which creates the temp-query and opens up the form WorkOrderInfoF.
The 4 tables are WorkOrdersT, ClientsT, UnitsT, and CustomersT. All have relations to eachother, in a straight forward line up of (all one to many from left to right)
ClientsT>CustomersT>WorkOrdersT>UnitsT. 1 Client can have as many customers which each customer can have as many work orders which any work order can have as many units.
The temp-query when made is called WorkOrderMoreInfoQ.
Lets jump right in. What happens is this:
There is a subform on the WorkOrderDatabaseF which lists the Work Orders; which which customers and clients belong to which work order. When you select one and click the more info button it pops up the WorkORderInfoF form and doesn't close the main database. From here it has text boxes, and another subform and button (the button won't be used for what I am asking so I won't go into detail about it). The text boxes currently are hooked up to show the data from the selected by a temp-query made when you clicked the button. It took the selection you clicked, and made a query which has 1 line with the information about that work order (the only foreign key in the workorderT is CustomerID which is related to the CustomersT key; which has a foreign key of ClientID which is as you guessed it, related to the key on ClientsT.) The text boxes show all the data correctly, except the CustomerName and ClientName. The subform would show all units that pertain to the workorder selected only. The popup form has the recordsource of the temp-query which I'm calling temp because when you close the more info form it deletes the query.
All code I have so far for things:
More info button:
Private Sub ProjectMoreInfoBtn_Click()
On Error Resume Next
DoCmd.Close acForm, "WorkOrderInfoF"
DoCmd.DeleteObject acQuery, "WorkOrderMoreInfoQ"
On Error GoTo Err_ProjectMoreInfoBtn_Click
Dim qdef As DAO.QueryDef
Set qdef = CurrentDb.CreateQueryDef("WorkOrderMoreInfoQ", _
"SELECT * " & _
"FROM WorkOrdersT " & _
"WHERE WorkOrderID = " & txtWorkOrderID.Value)
DoCmd.OpenForm "WorkOrderInfoF"
Exit_ProjectMoreInfoBtn_Click:
Exit Sub
Err_ProjectMoreInfoBtn_Click:
MsgBox Err.Description
Resume Exit_ProjectMoreInfoBtn_Click
End Sub
On form close delete temp-query code:
Private Sub Form_Close()
On Error Resume Next
DoCmd.DeleteObject acQuery, "WorkOrderMoreInfoQ"
End Sub
How would I make the customer and client name that is associated with tthe workorder be shown in their respective text boxes on the more info form? Also, how would I make only the units for the work order selected show up on the subform (datasheet) in the moreinfo popup form?
Why do you make your life so difficult... What if you create a temporary variable called tempWorkOrder which stores the workorderID as default value.
Afterwards, create a query based on that value and use it as a datasource for your 2nd form..The tempVariable should be set at your first form on the button control by using macro, preferably.
setTempVar
name:
Expression= workorderID(or textboxN.text)
EDIT: As we spoke yesterday..
Set qdef = CurrentDb.CreateQueryDef("WorkOrderMoreInfoQ", _
"SELECT * " & _
"FROM WorkOrdersT inner join WorkOrdersQ on workordersT.WorkOrdersID=WorkOrdersQ.WorkordersID " & _
"WHERE WorkordersT.WorkOrderID = " & txtWorkOrderID.Value)

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