Creating a form in Access to get the Customer Information - sql

I have created a database named Customer_master in which I have some customer information saved in an MS Access database.
I am trying to create a Form so that I can enter a Mobile Number and click the Search button and get the Customer Name.
The form is created with the Mobile Number & Customer Name as text boxes and a Search button in front of the mobile number.
As I am new to VBA, I think there is some coding issue.
Below is the code I have tried for the Search button:
Private Sub Command6_Click()
Dim strsearch As String
Dim Task As String
'Check if a keyword entered or not
If IsNull(Me.Mobile_Number) Or Me.Mobile_Number = "" Then
MsgBox "Please type in your search keyword.", vbOKOnly, "Keyword Needed"
Else
strsearch = Me.Mobile_Number.Value
Task = "SELECT Customer_Name FROM Customer_Master WHERE ((Mobile_Number Like ""*" & strsearch & "*""))"
Me.RecordSource = Task
End If
End Sub
After I enter the Mobile Number and click on the Search button nothing is happening as I am not getting the name of the customer.

An alternative way to achieve this is to create a new query in access against the datasource, and in the query definition pass the value from your search form to the query, using FORMS!VALUE.
You can then add a button to your form and save the VBA code to execute the query on click. by adding in the line DoCmd.OpenQuery

Related

Is there a simple code to allow certain user(s) access to see command buttons?

Okay, I am having difficulties coding security behind my user form. Let me give you guys the rundown. I created this make table "tblPermissionTypes" that basically has two field in there "ID" & "EmployeeType_ID". The ID field represents Security level of access 0 through 2, and EmployeeType_ID is the title: 0 = Requestor, 1 = Admin, and 2 = Printer.
With that being said I have another table "tblEmployees" with the same field "EmployeeType_ID", I manually set the 0s, 1s, & 2s. This table also contains all employees UserNames
Finally, I have another table "tblPermission" that contains three fields "EmployeeType_ID", "FormName", and "HasAccess"
My end result is being whenever this tblPermission has a Checkbox under the field HasAccess I want to grant access based on the EmployeeType_ID field to communicate back to the table "tblEmployees", but in this case I want them to only be able to see a button that contains that certain form.
Private Sub cmdClick_Click()
Dim strSQL As String
Dim permission As String
If permission = ("fOSUserName") = True Then
Run strSQL
strSQL = "SELECT * FROM tblEmployees WHERE "
strSQL = strSQL & "tblEmployees.Five2 =" & ("fOSUserName") & """, = False
Then
MsgBox "You do not have permission!", vbExclamation
Else'
cmdButton.Visible True
End If
NOTE: fOSUserName, is a function I created basically the same thing as
Environ("UserName")
Debug.Print strSQL
Function calls should not be within quote marks. You construct an SQL statement but then don't properly use it. You declare and use variable permission but don't set the variable - it is an empty string. Need form name as a search criteria. Couple of other syntax errors but they will go away with this suggested code. Run this code in form Open event to disable button and don't even give unauthorized users opportunity to click. Don't annoy them with a popup message that emphasizes their lowly status in hierarchy.
You need to build a query that joins tblEmployees to tblPermission so that UserName, FormName, HasAccess fields are all available then reference that query in search for permission.
A DLookup could serve here.
Me.buttonNameHere.Visible = Nz(DLookup("HasAccess", "queryNameHere", _
"UserName='" & fOSUserName & "' AND FormName='FormNameHere'"), 0)

append data from form to column

I am working on a "issue tracker" access data base where the user enters there data through forms, create new form and edit form.
I have a comment section on my edit form which I have been requested to remained lock, for viewing purposes. So the user can only view the comments.
I have another box below that must "append" or add data to the comment section with a time and user stamp.
My approach is to create a vba code that will allow the user to enter data, and once entered will show in the locked comment section. As the user is working through a "editing" form.
I am fairly new to access and vba and unfortunately I cant find anything that I understand online.
Below is some code use and found searching online. I have but can figure out how to append ( or add ) it to the existing column. It is running fine but the data value I wish to add don't go anywhere?
Private Sub Add_Click()
Dim StrSQL As String
Dim addComments As String
' where addcomment.value is the value desire to append
addCommentStr = Me!addComment.Value
'where IssueTrack is Table, AdditionalComments is column
StrSQL = "INSERT INTO IssueTracker(AdditionalComments) VALUES ('" &
addCommentStr & "' );"
DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True
MsgBox ("Comment Added")
End Sub
You wouldn't just keep on appending text to the same record. Where would you end?
So, skip all the code and create a form bound to the table.
Have one field for the date. Set its DefaultValue to: Now()
Set the form's property AllowEdits to: False

How to use VBA to add new record in MS Access?

I'm using bound forms for the user to update information on new or existing customers. Right now I'm using a Add New Record macro on the submit button (because I'm not sure how to add or save a new record through VBA).
I added a before update event (using VBA) to have the user confirm they want to save changes before exiting the form. For some reason this is overriding the add record button and now users cannot add new record until exiting the forms.
How can I use VBA to add new customer information to the correct table? Is this something that should be done with macros instead?
Form BeforeUpdate Code:
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim strmsg As String
strmsg = "Data has been changed."
strmsg = strmsg & " Save this record?"
If MsgBox(strmsg, vbYesNo, "") = vbNo Then
DoCmd.RunCommand acCmdUndo
Else
End If
End Sub
Add Record Button:
Private Sub btnAddRecord_Click()
Dim tblCustomers As DAO.Recordset
Set tblCustomers = CurrentDb.OpenRecordset("SELECT * FROM [tblCustomers]")
tblCustomers.AddNew
tblCustomers![Customer_ID] = Me.txtCustomerID.Value
tblCustomers![CustomerName] = Me.txtCustomerName.Value
tblCustomers![CustomerAddressLine1] = Me.txtCustomerAddressLine1.Value
tblCustomers![City] = Me.txtCity.Value
tblCustomers![Zip] = Me.txtZip.Value
tblCustomers.Update
tblCustomers.Close
Set tblCustomers = Nothing
DoCmd.Close
End Sub
In order to submit a record using VBA, create an On Click event for the button, and in that Sub run the following command:
Private Sub submitButton_Click()
'All the code to validate user input. Prompt user to make sure they want to submit form, etc.
DoCmd.RunSQL "INSERT INTO tblCustomers (CustomerID, CustomerName, CustomerAddressLine1, City, Zip) values (txtCustomerID.Value, txtCustomerName.Value, txtCustomerAddressLine1.Value, txtCity.Value, txtZip.Value)"
End Sub
In this Sub, you can add all the code you want to validate the values that the user entered and choose whether or not you want to submit the record. There's a lot of control using VBA to submit your forms, so you do not need a BeforeUpdate event.
Also, do NOT use bound forms with this method. I don't know what the repercussions are but I wouldn't try it. Access is great for starting off, but as you want to do more complex things, it is easier to just use VBA.
It seems strange that you would create a before update event for your form to create a prompt before closing. Perhaps you should try the on close event instead. If you want to use vba to add a new record from the form you can simplify your statement. I came across a similar situation when designing my own form for my Access DB. This code is tested and working:
Dim sVIN As String
Dim sMake As String
Dim sModel As String
Dim sColor As String
Dim sType As String
Dim intYear As Integer
sVIN = Me.txtVIN.Value
sMake = Me.txtMake.Value
sModel = Me.txtModel.Value
sColor = Me.txtColor.Value
sType = Me.comboType.SelText
intYear = Me.txtVehicleYear.Value
DoCmd.RunSQL "INSERT INTO Vehicles (VIN, Make, Model, VehicleYear, Color, Type) VALUES ('" & sVIN & "', '" & sMake & "', '" & sModel & "', " & intYear & ", '" & sColor & "', '" & sType & "')"
If you are just using one DB in your project and you're connecting on start up you can sometimes run simple DoCmd.RunSQL statements like this. You can take the syntax here and adapt it to your own project. I myself got the basic syntax from W3 schools. Good site for learning to write SQL queries. It should also be noted that validation testing is not included here. You should make sure it is included in the form validation rules or in vba code. One more thing... in your SQL it looks like you are attempting to assign a value to the ID column from a text box entry; if ID is an auto number column, don't do this. ID columns are usually assigned a number automatically, so you don't need to (or want to) specify an insert value for that.
As a side note:
I noticed that adding records via VBA functionality(as in your "Add Record Button" code) works ~400 times faster than using DoCmd.Run SQL "INSERT INTO...":
~55k records/s compared to 140 records/s for a table with 5 columns(ID+4 short strings).
This has no practical meaning in terms of a form, where data is entered manually but if the form is generating more records, this saves a lot of time.

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.

Creating a dynamic table from a combobox in Access

I am trying to set up a query where a field is searched for on a table, the table I want to select the information from will change each time. I have tables for different years of admission to a club (2011,2012 etc). I want a user to be able to select a year from a combobox on a form and then this dynamically change the table the data is being selected from.
The code I am using makes sense to me, but I am a novice. Access says there is a syntax error. Please help!
Code:
SELECT [Admission No#]
FROM [Forms]![Control Form]![YearSelect];
it would be better to use a filter.
Create a form (Continuous Forms or Datasheet) to show search result. You can open it or use as a subform.
Implement OnClick event for Search button.
Dim stFilter as String
stFilter = "age = " & Me.FLD_AGE
'-- first way
DoCmd.OpenForm "SearchResult", , , stFilter
'-- second way
With Me.SearchResult.Form '-- SearchResult is the name of SubForm control
.Filter = stFilter
.FilterOn = True
End With