Creating a dynamic table from a combobox in Access - sql

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

Related

Execute MySQL Select passthrough from a subform and send output recordset to a parent form

I manage a Microsoft Access 2019 Database (owned by a customer) with a form (named Mainform) whose recordset source is a MySQL passthrough query (SELECT * FROM table_on_mysql_db); each recordset (shown directly on opening Mainform) is only readable and it has three fields: one of them, description, contains text.
On double clicking on description field, a small sized subform (name Subform, containing one textvalue field named keywordDescr, plus an OK button and a Cancel button) pops up.
If I enter some words in keywordDescr (i.e. anyword) and press OK, the following passthrough query
SELECT * FROM table_on_mysql_db WHERE description LIKE '%anyword%'
is being called and the resultset ouput must be displayed in Mainform (Subform still remains opened); unfortunately, the Mainform content is not updated accordingly to the above MySQL filtered query.
The following is the VBA code called on clicking the OK button in Subform (OK is the label and the button name is button_search_description):
Private sub button_search_description_Click()
on Error goto ErrDescr
Dim qdfc as DAO.QueryDef
Dim qryPT as String
Dim ODBC_STRING as String
Dim kwd as String
kwd = Me.keywordDescr
kwd = Replace(kwd, "*", "%") '(the customer is still used to entering Access wildcard rather than MySQL wildcard!)
kwd = Replace(kwd, "'", "\'")
ODBC_STRING = "ODBC;DSN=MY_DSN_NAME" ' it works!
qryPT = "SELECT * FROM table_on_mysql_db WHERE description LIKE '" & kwd & "'"
DoCmd.setWarnings = false
Set qdfc = DBEngine(0)(0).CreateQueryDef("")
With qdfc
.Connect = ODBC_STRING
.SQL = qryPT
.ReturnsRecords = True
Me.Parent.RecordSource = qryPT
End With
Set qdfc = nothing
DoCmd.setWarnings = true
ErrDescr:
Resume Next
End Sub
Really doesn't make sense to modify query object and then set form RecordSource to that same SQL statement.
In design view, set form RecordSource to pass-through query object name or an SQL statement that uses pass-through query as source: SELECT * FROM PTQname;. Use code to modify pass-through query object to change parameters but don't change form RecordSource.
Finally, I solved the problem; #deluxeinformation gave me the right track, but I also wish to thank tho other users who gave me useful hints.
I defined a view on MySQL database named View_list, then set View_list as Mainform record source and, on Mainform load, the filtered PT query SELECT * FROM View_list WHERE F1 is executed, where F1 is the default filter where Mainform is loaded.
Similar PT query but with a different filter is being called clicking on the OK button in the Subform; the VBA code bound to this event is the following (kwd is the value entered in the input text keywordDescr of the subform Subform):
qryPT = "SELECT * FROM View_list WHERE description LIKE '" & kwd & "'"
With qdfc
.Connect = ODBC_STRING
.SQL = qryPT
.ReturnsRecords = True
Forms!Mainform.RecordSource = qryPT
End With
It's a little confusing to me what you're trying to do here but as I understand it you have a pure MySQL query (PTQName) that is the recordsource of a form (MainForm) when it is first opened. Right now this is a passthrough query defined in Access but not in MySQL. Then you want to be able to open a pop up form to filter the results you get from PTQName in MainForm. What I would do first is take the code for PTQName and create an actual view in MySQL Workbench from this (for example, call it "MyView"). Then link that view into your Access database. Access will treat this MySQL view as just another linked table. Set the recordsource of your MainForm to the name of this view so when it opens it displays records from your view. When you want to filter the records shown in your MainForm using your popup form, either use MainForm's Filter and FilterOn properties, or set MainForm's recordsource = "select * from MyView where ...". I am not seeing a need to even use a pass-through query here, let alone modify its SQL at runtime. But if I am misunderstanding please let me know!

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

Creating a form in Access to get the Customer Information

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

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

Design an Access Form to Use Different Queries

I had an Access Form that works very well for my customer, however they want 3 identical forms, but with different underrunning queries for different types of searches. I could copy and paste the same form and attach the different queries, but this can become a huge maintenance and maintainability issue. Is it possible to use multiple queries on the same form, or change out the query before opening the form?
It sounds like your different queries all return the same SELECT field expressions, but have different WHERE clauses.
If that is true, use a base query without a WHERE clause as the form's Record Source. Then you can essentially add a WHERE clause "on the fly" by using the DoCmd.OpenForm method's WhereCondition option when you open the form.
Const cstrForm As String = "YourForm"
Dim strWhereCondition As String
Load strWhereCondition based on which dataset you want the form to display. These 3 examples assume the form's Record Source includes fields named proj id, proj name, and owner id whose datatypes are numeric, text, and numeric respectively:
strWhereCondition = "[proj id]=" & SomeNumber
strWhereCondition = "[proj name]='" & SomeText & "'"
strWhereCondition = "[owner id]=" & SomeOtherNumber
Then open your form filtered by strWhereCondition:
DoCmd.OpenForm FormName:=cstrForm, WhereCondition:=strWhereCondition