I have a form (Purchase Orders) and a sub-form in it
(Purchase Order Details). The Main form contains Number of the
PO (text box), Supplier (combo-box), Employee (combo-box),
Status (combo-box) which contains 2 records (New and Done) and a date box (when the PO was created). The Sub-form (datasheet) contains Product (combo-box), Quantity and a Price field.
What I want to do is to add a button on the main form which will do
next.
When the button is pressed a VBA code should be executed and do next.
Take data from the Main form (Number of the PO, Status and the date)
and the Sub-form (Product, Quantity and Price) and put all that into
a table (StockMovements).
I managed to do that with the next code:
Private Sub cmdOrder_Click()
Dim strSQL As String
strSQL = "INSERT INTO StockMovement (ID_Product, Status, Quantity, ID_PurchaseOrder) VALUES (" & _
Me.frmPurchaseOrderDetails_Subform.Form!comboboxProduct & ", '" & _
Me!txtStatus & "', " & _
Me.frmPurchaseOrderDetails_Subform.Form!txtQuantity & ", " & _
Me!txtID_PurchaseOrder & ");"
DoCmd.RunSQL strSQL
Me.Requery
End Sub
However, there are 2 problems:
As you can see I didnt add the date field because I get an error,
cant remember which one it was exactly but I think 2075;
The code works without the date, but only adds one Product to the
table, the first one. And in a Purchase Order there are usually more
than one products.
Because Im totally new in VBA, I would kindly ask you to treat me like a newbie and explain more detailed, if possible.
(Fixed the code, forgot to change the language. I mean I pasted the wrong one, now its the right one but still not working of course :))
Thanks!
1) If you only have a problem with one specific field, I would check whats special with that one. Probably the input is formatted as a string and the field as Date/Time. In that case try to use the CDate()-Function. I could imagine, that a .Value at the end could solve the problem, too.
Dim datDate as Date
datDate = CDate(Me!txtDate.Value)
2) That your code inserts only one row is absoluterly correct. Remember that e.g. Me!txtStatus.Value is a textbox that contains only one single piece of data. The rows of data are saved in a table and depending on the row you have selected with a main-form (= one row), the corresponding value is shown in the textbox.
INSERT INTO table (field1,field2) VALUES (value1,value2)
An INSERT INTO inserts one row every time it's executed. So the SQL in the code you have mentioned needs to be repeated. You could do so using loops.
Dim strSQL As String
strSQL = ""
For Each Item In Group
strSQL = strSQL & "INSERT INTO table (field1,field2) VALUES (value1,value2)"
Next
In my opinion, copying data that way is absolutely annoying with VBA. You need to create recordsets, modify and merge them. I would try to solve as much as possible with Access Non-VBA-Solutions.
My question to you: Did you think about linking the form (and sub-form) directly to the table(s)?
The date can be inserted this way:
"INSERT INTO StockMovement ([DateField]) " & _
"VALUES (#" & Format(Me!DateField.Value, "yyyy\/mm\/dd") & "#)"
That said, your code will insert one record only. To insert multiple records you need a select query or - much faster - use DAO to open the target table as a recordset and then, as source, loop the RecordsetClone of your subform and copy the records to the target table one by one.
Related
I cant post too much detail due to sensitive info so I will define the problem as seen below.
I have:
Table1 = read only table containing uID & other employee info
Table2 = new table created from form, using a combination of Table1 data and user input data
QueryTable1 = Query pulling relevant data from Table1 such as employees in particular department
FormA = form reading QueryTable1 to allow user to select their user id "uID"
uID = employee number and a field on Table1, Table2 and combobox on form
I am currently getting uID from QueryTable1 and populating results as options in FormA combo box. When I select a uID from the list, it pulls all data and displays to the user properly and unique to that uID. When I click Save Record it saves the FormA data to Table2. This works, however my issue is that the data populating Table1 is not the same data displayed on FormA, it is populating the same uID no matter what is selected and displayed in the FormA. The uID being populated in Table2 appears to be the lowest uID and whatever is messing up is therefore returning results based on Ascending Query.
I can't figure out how to resolve this. Selecting a control source on FormA and setting it to uID results in the value being unselectable on the combo box. Other than being unselectable, all values in the combobox appear the same as when it has no control source. Again this combo box is being populated by QueryTable1 data.
Here is my code sending data from FormA to Table2:
Dim strInsert As String
strInsert = "INSERT INTO [TABLE2] (uID, a, b, c) VALUES(" & Me.uID & ", " & Me.a & ", " & Me.b & " , " & Me.c & ")"
CurrentDb.Execute strInsert
Final example of my steps:
in FormA I select my combo box and see uID values: apple, orange, pineapple
I select pineapple, all other fields on the form populate correctly related to pineapple
I click save and the code above executes
I then refresh Table2, the value populated in uID field = apple and it should have been pineapple
Thank you for any help and I am sorry I cant post more specific info/screenshots.
I answered my own question on accident right after posting due to the code editor saying the format was wrong and showing date format which is a hidden column 0 in my combo box, and my uID is column 1. The code below resolved it, but if anyone has a better method I would appreciate your thoughts.
My combo box actually has several columns contained in it because I found that to correctly drive some of the data it populates later on the form. For this reason there are multiple columns visible and invisible in the combo box. I have a suspicion that this is not efficient. But it is working for now and thats ultimately what matters right?
Dim strInsert As String
strInsert = "INSERT INTO [TABLE2] (uID, a, b, c) VALUES(" & Me.combouID.Column(1) & ", " & Me.combouID.Column(2) & ", " & Me.combouID.Column(3) & " , " & Me.combouID.Column(4) & ")"
CurrentDb.Execute strInsert
I have an issue for which I cannot seem to find an answer (I am new to this and clearly I do not know how to create an append query properly...)
I have a table "Basket" in which I create new lines each week on a form.
Each time I create a new "basket", I want my "follow basket" table to be incremented with a new line, attached for each customer following the proper conditions (of my table "customers").
So I need a query (i think) that copy the data from "basket" in the "follow basket" for each "customer" where its conditions match the "basket"'s.
Do you see what I mean ?
Example :
I create basket "Type P" for week S1
It creates week S1 basket in "follow basket" for each customer who subscribed for basket "Type P".
In "follow basket" I can then say if they had their basket delivered and paid.
Thank you for your help...
Here is my database structure as asked
Panier : basket
suivi_paiement_panier : follow basket
Particuliers : customers
I also have a "semainier" field (weeks) because we create specific baskets each week and all the follow up is made like that (S1, S2, ... = Week1, week2...)
You want to 'batch create' a set of new records based on new data as well as existing data. An INSERT SELECT SQL statement is commonly used to accomplish that.
Multi-value field Type_de_panier complicates but it is manageable.
Another complication is referencing form controls to pull criteria parameters because likely form/subform arrangement is involved in data entry and parameters are sourced from different forms. If you have Samainier as main (parent) form and Panier as subform and code is behind Panier form, consider:
DoCmd.RunCommand acCmdSaveRecord
CurrentDb.Execute "INSERT INTO Suivi_paiement_paniers(IDDate, IDT1) " & _
"SELECT " & Me.Parent!Semainier_IDDate & " AS SID, IDT1 FROM Particuliers " & _
"WHERE Fréquence='" & Me.Parent!Paire_Impaire & "' AND Actif=True " & _
"AND IDT1 IN " & _
"(SELECT IDT1 FROM Particuliers WHERE Type_de_panier.Value='" & Me!Type_Panier & "')"
Make adjustments if your form arrangement is different.
Now have to figure out what event to put code into. If you want to rely on user to initiate this action, then use a button Click.
I've looked around for an answer to this issue, but have fond none. Thank you in advance to anyone who's able to help. I'm trying to look up records and alter them, based off multiple fields. However, my form shows up blank.
I have a database with one to many links for the following tables:
Sample->Set->Catch->Length->Diet (Key fields: SampleID, SetID, etc.)
Preliminary data is entered. I have additional data for some individuals to be entered into the Length and Diet tables. So, I created a form with combo boxes that allow the user to navigate to the correct fish by selecting: Date, Station, Set, Species, and Length. So, when I select a date, I'm restricted to stations sampled on that day and so on. I have a query string set up to restrict results to those matching the criteria entered into the combo boxes. My subform is based off the final query in this string (Query 5). It's linked on the primary key field for the length table (LengthID). All fine so far.
The issue: When I open my form and select values for each combobox, the subform remains blank. However, I can run Query 5 from the sidebar at this point and it runs successfully. I could just enter data directly into the query, but it would be less streamlined and vulnerable to human error.
I've also tried opening my subform directly from the sidebar. When I do this, Access prompts me for the Date, Station, Set, Species, and Length. Twice. The form then shows up and all are fields blank including the LengthID field, which should be filled in (since I'm looking up an existing record). I don't know why it prompts me twice, but I think that the subform isn't showing up in regular form view because the database sees the LengthID field as blank.
My combo boxes appear to navigate correctly to a given record. The query string my combo boxes and subform are based on all work when run directly. But I can't enter data into my subform, presumably because the subform can't find the correct record even though the query it's based off of can find it just fine. I've run out of troubleshooting ideas, any advice is greatly appreciated. Thanks!
If I understand correctly, you're trying to achieve a query WHERE clause utilizing combo-boxes. There are many SO questions out there on this but this should get you going. Let me know if you run into trouble and I'll help you out.
I assume you have a linked parent/subform combo. This code would be on the parent form search button:
Dim strSQL As String
strSQL = " 1=1 "
If Not IsNull(cmbComboBox1) Then
strSQL = strSQL & " AND Field1 = " & cmbComboBox1
End If
If Not IsNull(cmbComboBox2) Then
strSQL = strSQL & " AND Field2 = " & cmbComboBox2
End If
If Not IsNull(cmbComboBox3) Then
strSQL = strSQL & " AND Field3 = " & cmbComboBox3
End If
Me.Filter = strSQL
Me.FilterOn = True
I have sub that runs when the database is opened to a specific form and I'm trying to get it to add information in a table.
The table name is UnAuthorizedAccess and the columns in table are ID(auto number), NAME(text), COMPUTERNAME(text), ATTEMPTDATE(date/time).
What commands do I need to use to add a new record to this table? I have a VBA that if they're login information Isn't there is will force close access all together. I'm trying to gather information on the user as well before kicking them out.
I figured this is the easiest way as outlook won't let you send a hidden email from the user unless they first see it.
You can add records to a recordset with the following code, but I am unsure whether you have a field called COMPUTERNAME. You shouldn't need to add the ID value as its an autonumber.
dim Rst as recordset
Set Rst = CurrentDb.OpenRecordset(Name:="UnauthorizedAccess", Type:=RecordsetTypeEnum.dbOpenDynaset)
With Rst
.AddNew
![NAME] = Me.Name.Value
![COMPUTERNAME] = Me.COMPUTERNAME.Value
![ATEMPTDATE] = date()
.Update
End With
As for sending hidden emails, see this question I asked not so long ago. It sends an email via outlook, but remember to reference the Microsoft Outlook Object library in the VBA Editor.
CurrentDB.Execute is the method for executing SQL statements, and INSERT INTO is the SQL statement for adding records to a DB table.
CurrentDB.Execute "INSERT INTO UnAuthorizedAccess (NAME, COMPUTERNAME, ATTEMPTDATE) " & _
"VALUES (" & Your_NAME_Variable & ", " & Your_COMPUTERNAME_Variable & ", " & Now() & ")
Replace Your_NAME_Variable and Your_COMPUTERNAME_Variable with the variables in your code containing these values.
I have found similar answers to this question, even on this site, however, the syntax has not worked for my database and I'm not sure what needs to be done. This data base is used to house audits for staff performance and accuracy. I am now in the midst of creating the forms and getting them to flow properly for the user.
When conducting an audit, the user will need to enter six specific fields into the first form. Those forms are Audit, Month, Year, Username, Location, Reviewer, and Date. The user will need to complete multiple audits, however, these six fields will always be the same.
I would like to copy these fields in the first form and carry them into the second form so the user does not have to repeat the information. Here is my current code (set to run on the click of a command button on the bottom of screen 1):
Dim strSQL As String
strSQL = "INSERT INTO [tblTripMem] (Audit, Month, Year, Username, Location, Reviewer, Date)"
strSQL = strSQL & " Values (" & Me.cboFP1Audit & "," & Me.Month & "," & Me.Year & "," & Me.Username & "," & Me.Location & "," & Me.Reviewer & "," & Me.Date & ") FROM [FPScreen1]"
strSQL = strSQL & "WHERE (currentrecord = " & Me.CurrentRecord & ")"
DoCmd.RunSQL (strSQL)
Each time I run this I receive the following error: "Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.
I am new to Access and am unsure of what this means or how to fix it. All I know is that I'm not finding a solution. Can anyone help? I'd greatly appreciate it.
Here's a mock-up Access file illustrating a way to do what you're doing without using SQL:
With Form 1 open...
...complete the various fields:
Click the Copy to Form 2 button and this will open Form 2 and populate its fields with the data from Form 1:
Here's the VBA code on the Copy to Form 2 button's OnClick event:
Private Sub cmdCopyToFrm2_Click()
Dim frm As Form
DoCmd.OpenForm "Form2"
Set frm = Forms!Form2
With frm
!AuditRef = Me.cboFP1Audit
!AuditMonth = Me.txtAuditMonth
!AuditYear = Me.txtAuditYear
!AuditUsername = Me.txtAuditUsername
!Location = Me.txtLocation
!Reviewer = Me.txtReviewer
!AuditDate = Me.txtAuditDate
End With
End Sub
Note that when Form 2 opens, the textbox that the cursor defaults to might not seem to show any data; if you move away from that textbox it should magically show (don't know why it does this, but there you go).
INSERT INTO table (...) VALUES (...) cannot have a FROM or WHERE clause. You insert a single record with fixed values, not data from another table.
But once you delete these clauses, you will have other errors, because you need to format your string and date values correctly to get the INSERT query to work.
And then you will still be prone to SQL injection errors. It is safer to use Recordset.AddNew and .Update to add records.
See e.g. here: https://stackoverflow.com/a/34969410/3820271
(but without the loop)