How to make an if statement to stop access from running query? - sql

I'm using Microsoft access and I want to make an if statement that basically does:
if the search criteria are all blank, then open a message box that says "something I write" and an OK button. The ok would throw you back to the search from and not run query.
My issue is that if all of the search criteria are left blank and someone hits search, it'll crash access. So I wanna make something that'll stop someone from running the query in blank. I am using a form with 6 different criteria's called Standards, Duds, ID, Desc1, Desc2, and Excel.
Just to let everyone know too, I am pretty stupid when it comes to coding and stuff so if you could spell it out in a way a 4 year old could understand that'd be great.
I would like something that reads:
If [Forms]![Search]![Standards] AND [Forms]![Search]![CADID] is blank then
MsgBox("You cant do this") - and then this would send you back to the form
ElseIf
Run the query normally.
Currently my code looks a bit like:
SELECT DISTINCT Standards.Name, Standards.[Catalog Id], - then a bunch of other tables and their respective columns
WHERE(((Standards.Name)Like"*"& [Forms]![Search]![Standards] & "*") AND ((Standards.[Catalog ID]) Like "*" & [Forms]![Search]![CADID] & "*"));
I dont know why it ends there. Where it reads [Standards] and [CADID] after WHERE are the text boxes a user and write in a form.let me know how much more detail you need.

Not sure what your search code is, but here's a template to work with. Put this in the On-click event of the button that executes your search and make sure you add whatever code executes your search in place of the comment I've left in the else part of the If statement below.
If _
(IsNull([Forms]![Search]![Standards]) Or _
[Forms]![Search]![Standards] = "") And _
(IsNull([Forms]![Search]![CADID]) Or _
[Forms]![Search]![CADID]) = "" _
Then
MsgBox "Please complete both Standards and CADID fields before searching", vbCritical Or vbOKOnly, "Search Error"
Else
' your search code here
End If

Related

Escaping special characters in Microsoft Access 2016

I am working on a project for the company I work for, designing a database to keep track of and create project numbers. I have it up and running, but my supervisor has asked that I include user-input sanitizing to escape special characters that could cause a problem for the existing code and SQL. I have a few different user-input forms, which are just bound text boxes which get entered into my table when the form is closed. I also have one Input Box, which asks for the project number which an employee would like to update the info for.
From my understanding, a local Access database on our company server is not going to be very prone to SQL injection, and MS Access has a way of handling injection which I do not really understand. However, I am looking for a list of characters which could potentially cause problems, where they could potentially cause problems, and the best way to deal with them.
I have tried inputting a few different special characters which I know to be problematic into the text boxes on the forms, but Access just parses them straight into the record, with no errors. I DO have one function written in which replaces single apostrophes with two apostrophes, and this is used on the InputBox.
Here is the code behind the InputBox:
Private Sub btnOpenUpdate_Click()
Dim strInput$, safeInput$
strInput = InputBox("Enter the EP-Number for the project that you would like to update:", "Update Project")
safeInput = safeEntry(strInput) 'change all single apostrophes to double apostrophes '
If Len(safeInput & vbNullString) > 0 Then
If DCount("EPNumber", "tblProjects", "EPNumber = '" & safeInput & "'") > 0 Then
DoCmd.OpenForm "frmUpdateProject", , , "EPNumber = '" & safeInput & "'"
Else
MsgBox "Please enter a valid EP-Number.", vbInformation, "Error: Invalid EP-Number entered"
End If
Else
MsgBox "The field was left blank. Please enter a valid EP-number.", vbInformation, "Error: Empty field"
End If
End Sub
And here is the code behind the safeEntry function:
Public Function safeEntry(strEntry)
safeEntry = Replace(Nz(strEntry), "'", "''")
End Function
Apologies for the somewhat lengthy summary of my situation, but any help and input would be very appreciated, as I am fairly new to the world of MS Access and SQL, and I am trying my best to learn how to protect the database.

MS Access Issue

Hello Stackoverflow community!
I have run into an issue and I'd love some advice.
I'm working with MS Access and I am trying to append two particular fields from one table to another; however this implementation is in a form and it gets a little complicated... So, I'll explain everything the best that I can
BACKGROUND INFORMATION:
First and fore most, I have two tables; one of which is a linked excel spread sheet from another directory (who is not willing to change any formatting what so ever, so I CANNOT make ANY changes to this file and it is being updated on a daily basis). This excel spreadsheet is very large and contains somewhere around 50 columns
The other table is not anywhere near as large but has around 20 columns and is meant to extract two columns from the excel spreadsheet (the first column and the third column). I'm trying to make a form for this database to be as user-friendly as possible and not many people in my office are familiar with the technicalities of Access queries and programming in VBA.
THE SITUATION:
On my form, the user will enter data into TextBoxA, from there they will click a button; this button will trigger a search through the linked excel spreadsheet for the data that was typed into TextBoxA. It will then copy the data from Field1 (which was the typed data) and Field3 and append these selected fields into the first two fields of the table in my Access Database. All of this is being done through a segment of VBA code
Private Sub CmdCloseForm_Click()
If IsNull(Me.TextBoxA) Or Me.TextBoxA = "" Then
MsgBox ("Field is empty, please try again!")
Else
Dim VendorNum As String
SearchingValue = Me.TextBoxA
Dim SQL As String
SQL = "INSERT INTO tbleRecord (Field1,Field2)" & _
"SELECT * " & _
"FROM tbleLinkedExcel " & _
"WHERE Field1 = '" & SearchingValue & "';"
DoCmd.RunSQL SQL
End If
End Sub
So the biggest issue here is that in Field1, and every time I try to run the code,
I receive an error; which I am assuming it is because of the space (unfortunately I cannot give the ACTUAL variable names out as it is confidential)
ERROR MESSAGE
The INSERT INTO statement contains the following unknown field name: 'FIELD 1'. Make sure you have typed the name correctly, and try the operation again.
The thing is, is that this 'FIELD 1' variable/name is not in my code, but in the linked excel spreadsheet (again, I am not able to change ANYTHING on this spreadsheet).
Thanks guys!

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

Run a Query Using a Button in Access

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.

Use toggle buttons to update a record in Access

Hopefully not too difficult question but I cannot figure this out and have been unable to find anything searching the forums.
I want to convert the output of my toggle boxes from 1,2,3,4,5 to the text each button displays.
Couldn't find any setting on the toggle boxes properties themselves so decided I would have to write a macro/vba to do it from the table but as it's quite new to me I am struggling on syntax.
I have tried doing this on the inbuilt data macro mainly, but also tried it via a query and vba and still couldn't figure it out.
[don't have any reputation yet so have not been allowed to post pics of my macro attmept]
please help! Any solution using vba, data macro or a query would be great
EDIT
To be specific rather than a message box I want to update field1 in my table "Major Equipment" based off the option group selection this is my latest attempt but still not sure how to reference the option group. Do I need to set grp equal to the option group and if so how? Is it something like forms!myform!optiongroup ?
Option Compare Database
Function MyFunc(grp As OptionGroup)
Dim rcrdset As Recordset
set grp =
Set rcrdset = Application.CurrentDb.OpenRecordset("Major Equipment", dbOpenDynaset)
Select Case grp.Value
Case 1
With rcrdset
.AddNew
![Field1] = "Not Reviewed"
Case 2
.AddNew
![Field1] = "Reviewed"
Case Else
MsgBox "Error"
End Select
End Function
Also just realised since these toggle buttons will be updated by the user and so I probably need an update rather than addnew?
http://i59.tinypic.com/2ym8wet.jpg
Your buttons are part of an Option Group. That is what you must reference. Below is a snippet from my net search.
From the AfterUpdate() event of your Option Group:
Call MyFunc(Me.MyGroup)
... which will use Select Case to evaluate:
Function MyFunc(grp As OptionGroup)
Select case grp.Value
Case 1
MsgBox "Option value is 1."
Case 2
MsgBox "Option value is 2."
Case Else
MsgBox "Huh?"
End Select
End Function
If you are entirely new to VBA, there are a half-dozen things to learn here, but they will serve you well. VBA provides a bit less-friendly-looking start than a macro, but I can tell you have more adventures ahead and I suggest you skip macros. For most needs, VBA will serve you better; and it's much easier to trouble shoot or provide details when you need advice.
To convert this to a useful function, you will fill a string variable rather than raising a message box. Then you can use the string variable to do something like run an update query. Your latest edit suggests you will go for something like:
strSQL = "UPDATE [Major Equipment] " _
& "SET Field1='" & strUserSelection & "' " _
& "WHERE MyID=" & lngThisRecord
DoCmd.RunSQL strSQL
Your last edit proposes using a DAO recordset. I think you might be fine with the humble DoCmd. Less to learn. You can hammer out a prototype of the query in good ol' Access; then switch to SQL View and paste the query into your VBA module. Insert variables as seen above, taking care with the quote marks. If it doesn't work, use Debug.Print to grab the value for strSQL and take that back to good ol' Access where you can poke at it into shape; use your findings to improve the VBA.