Access: dynamically query tables - sql

I built an Access database to contain information regarding parts that we use to create schematics. There is one table that contain "basic" information, like "unique part ID" ("TUPID"), links to datasheets and so on - and the "Partition" further information is stored.
Furthermore there are several tables (this is "Partition") that contain information on the part itself: one table for resistors, one for connectors, one for power-ICs and so on. Each table has many fields different from other tables, but there are fields that exist on each table, eg. "Manufacturer", "Symbol", "Package" and "Height".
Now I have a split form ("10_Change_BaseInformation") that shows the "basic information", so when I select one row in the database-part of the form, the data is loaded into textboxes and can be edited. Additionally I want to see the information from the "Partition"-table in this form, so I wrote this:
Private Sub Form_Click()
Dim SelectedPartition As String: SelectedPartition = Forms![10_Change_BaseInformation]![Text25]
'Field "Text25" contains the TUPID
Dim SQLStatement As String
SQLStatement = "SELECT " & SelectedPartition & ".TUPID, " & SelectedPartition & ".[Mfg]" & vbCr & _
"FROM " & SelectedPartition & vbCr & _
"WHERE (((" & SelectedPartition & ".TUPID)=[Forms]![10_Change_BaseInformation]![TUPID]));"
DoCmd.RunSQL SQLStatement
' SQLStatement = "SELECT Resistor.TUPID, Resistor.[Hersteller] FROM ResistorWHERE (((Resistor.TUPID)=[Forms]![10_Change_BaseInformation]![TUPID]));"
End Sub
First of all, I get runtime-error "2342", but I can't make any sense of that; so: how do I have to modify my code, to get a valid result?
Second, how can I get the values from the query to the form?
Thanks in advance for your help!

I can't speak to the reason of your error, as we would need more information such as the types of your fields in your table.
I'm guessing that your Resistor.TUPID field is a string.
If so, you need to modify your code as below:
WHERE (((" & SelectedPartition & ".TUPID)='" & [Forms]![10_Change_BaseInformation]![TUPID] & "'));
If it is of Type number then
WHERE (((" & SelectedPartition & ".TUPID)=" & [Forms]![10_Change_BaseInformation]![TUPID] & "));
As to the form...
Generally speaking, you can design a form without a record source, but with controls that are named the same as your select query fields.
When designing each Control on the form, you have to explicitly specify the Control Source (i.e. The field names that are returned from your select query), otherwise they will be Unbound and never update automatically based on Record Source.
Then assign your SQL query string to the Recordsource of the form.
MyForm.Recordsource = MySQLString
Then run the Requery method of the form.
MyForm.Requery

Related

SQL Syntax error running action Query through VBA

I am trying to build this query through VBA instead of building it in Access and running a docmd.openquery. That seemed to me like the easier route, but I wanted to work on my SQL. Obviously that didn't work as intended if I am here lol.
So, I am trying to take the Date values of 14 text boxes on our JobTicket form and insert them into another table, Tbl_Schedule. This table is not a part of the Query that is the record source for the JobTicket form. I am worried that attempting to add this table in will overload the Query, as it is already very full. When I try to quickly navigate to the last field in that Query the text writes on top of itself, and then Access goes not responding while it clears up the text and loads the last couple fields. Adding another 56 fields to that seems like a recipe for disaster. I will post the SQL I have written below.
DoCmd.RunSQL "INSERT INTO Tbl_Schedule (Date_Scheduled1, Date_Scheduled2, Date_Scheduled3, Date_Scheduled4, Date_Scheduled5, Date_Scheduled6, Date_Scheduled7, " & _
"(Date_Scheduled8, Date_Scheduled9, Date_Scheduled10, Date_Scheduled11, Date_Scheduled12, Date_Scheduled13, Date_Scheduled14)" & _
"VALUES (#" & [Forms]![Frm_JobTicket]![Txt_DateScheduled1_JobTicket] & "#,#" & [Forms]![Frm_JobTicket]![Txt_DateScheduled2_JobTicket] & "#, " & _
"(#" & [Forms]![Frm_JobTicket]![Txt_DateScheduled3_JobTicket] & "#,#" & [Forms]![Frm_JobTicket]![Txt_DateScheduled4_JobTicket] & "#, " & _
"(#" & [Forms]![Frm_JobTicket]![Txt_DateScheduled5_JobTicket] & "#,#" & [Forms]![Frm_JobTicket]![Txt_DateScheduled6_JobTicket] & "#, " & _
"(#" & [Forms]![Frm_JobTicket]![Txt_DateScheduled7_JobTicket] & "#,#" & [Forms]![Frm_JobTicket]![Txt_DateScheduled8_JobTicket] & "#, " & _
"(#" & [Forms]![Frm_JobTicket]![Txt_DateScheduled9_JobTicket] & "#,#" & [Forms]![Frm_JobTicket]![Txt_DateScheduled10_JobTicket] & "#, " & _
"(#" & [Forms]![Frm_JobTicket]![Txt_DateScheduled11_JobTicket] & "#,#" & [Forms]![Frm_JobTicket]![Txt_DateScheduled12_JobTicket] & "#, " & _
"(#" & [Forms]![Frm_JobTicket]![Txt_DateScheduled13_JobTicket] & "#,#" & [Forms]![Frm_JobTicket]![Txt_DateScheduled14_JobTicket] & "#)"
Table being inserted into: Tbl_Schedule
Fields being inserted into: Date_Scheduled1 -to- Date_Scheduled14
Getting data from text boxes: Txt_DateScheduled1_JobTicket -to- Txt_DateScheduled14_JobTicket on Frm_JobTicket
Any other questions that would assist you in assisting me please feel free to ask! Thanks in advance!
Dynamic SQL has its uses, but this is not one of them.
Using DAO methods makes your code so much simpler and easier to read and debug.
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim frm As Access.Form
' for readability
Set frm = Forms!Frm_JobTicket
' open table for adding record(s)
Set db = CurrentDb
Set rs = db.OpenRecordset("Tbl_Schedule", dbOpenDynaset, dbAppendOnly)
rs.AddNew
rs!Date_Scheduled1 = frm!Txt_DateScheduled1_JobTicket
rs!Date_Scheduled2 = frm!Txt_DateScheduled2_JobTicket
' etc.
rs.Update
rs.Close
With enumerated field names like these, you can also use a loop:
Dim i As Long
rs.AddNew
For i = 1 To 14
rs("Date_Scheduled" & i) = frm("Txt_DateScheduled" & i & "_JobTicket")
Next i
rs.Update
This is a good opportunity to consider normalizing your data so that part of your problem is removed entirely. Instead of having DateScheduled1_JobTicket, DateScheduled2_JobTicket etc., it might be better to have another table which fills vertically instead of horizontally, perhaps with fields like ID, Item, JobTicketNumber, ScheduledDate.
Then, fill this table with a row for each item/sku/product, and date. You'll have 14 rows for scheduled tickets for each item/sku/product instead of 14 columns, and this will also solve your future problem of adding 56 fields. The benefit is that you can present the job ticket schedule rows by using continuous forms (in a list). Even better, you can put this continuous form with dates as a subform on your item/sku/product main form, which will then show as a neat list of scheduled tickets that will automatically change as you scroll through item/sku/products.
If you don't use continuous forms, you can still use an unbound approach as you're using now. One benefit is that it will be much easier when you need to add future JobTicket numbers, since you can just add more rows instead of adding fields and having to do additional design work.
If you want to view data in the flattened way that you built your table, you can use a Crosstab query to present it as you have in your table, but the underlying data will be much better stored in a normalized format.
Note that you don't need to concatenate a string as you did above; just leave the Forms!Form!Control reference expression directly in the query and you have a nice parameterized query that will execute just fine, so long as there are dates in those controls (text box, drop down etc).
ex.
Insert Into (MyDateField) Values (Forms!MyForm!MyDateControl);
No dynamic SQL needed.

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.

Referencing Variable for Functions

Every two weeks there will be a new table with new data coming in to me, I need to update that onto a master table. I want to automate this process.
I would like to declare a variable that a user can input the date the data is from, and based on that date update to the appropriate field on the master table. I have no clue how to make SQL functions use variables to locate tables with the syntax, not even sure if this can be done. Any help would be appreciated.
As I am inexperienced, I am making a VBA Macro and embedding the SQL code from the access query I made.
Sub UpdateFieldX()
Dim SQL As String
SQL = "UPDATE [15-Jun-16] " & _
"RIGHT JOIN MasterSPI " & _
"ON [15-Jun-16].[SR#] = MasterSPI.[SR#] " & _
"SET MasterSPI.[30-Jun-16] = [15-Jun-16].[SPI]; " _
DoCmd.RunSQL SQL
End Sub
I've done something similar to this and used an Update Query and Insert Query.
It sounds like you're trying to just update any existing records that may need updating and then adding new records into the table.
For an update, I'd try creating a query in SQL view and type something like:
UPDATE MasterSPI SET MasterSPI.SRnumber = [newtablename]![SRnumber] etc.
and do that for each field in your table.
For inserting you could do something like:
INSERT INTO MasterSPI SELECT * FROM newtablename
That may help you get started.
I know many of you are advanced users but I found an answer that fit my quick needs. As a notice and disclaimer for other people, it will be in no way secure, it is more for personal use such that I do not need to spend an hour doing append and updates to several master tables repetitively.
To do this, I made a global string variable called name, then I made another variable called strung that translated it into a readable string for referencing. I then made an SQL string that references that strung variable. This allows the user to submit an input for the global variable, which translates into a readable string for the RunSQL method.
Here's a snippet of the parts that were most relevant, I hope it helps whoever comes next with the same scenario.
**
Public name As String 'global variable declared so that the new field to be created can be used elsewhere
name = InputBox("Name of Month", "InputBox") 'variable that takes user input and it will be name for new fields to be added
Dim SQLa As String 'creates a string variable such that it will be read as an SQL line by the RunSQL method
strung = "[" & name & "]" 'sets strung as global varible name, which is user input on the specific table being used to update
'the following lines runs a query such that it updates the master table with new data and does the grouping by SR number
SQLa = "UPDATE " & strung & " " & _
"RIGHT JOIN MasterSPI " & _
"ON " & strung & "." & "[SR#] = MasterSPI.[SR#] " & _
"SET MasterSPI." & strung & " = " & strung & "." & "[SPI]; " _
DoCmd.RunSQL SQLa 'executes the SQL code in VBA **

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.