Create new lines in a database based on a condition - ms-access

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.

Related

MS Access VBA Writing to a table from a form

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.

MS Access Simple form to populate many to many table

I have a simple ms access db with the following tables:
Patient
ID
Name
Medication
ID
Name
PatientMedication
ID
PatientID
MedicationID
This third table is a many to many table between Patient and Medication - recording what medications are taken by each patient. I want to create a form that populates this table by allowing me to select a patient and a medication, and storing a new row to the PatientMedication table.
I've gotten as far as creating the form with the dropdowns, and added a button to save the selected rows to the db, but don't know how to make the button do the insert. Do I have to write some VB code for the button? Do I even need a button? It seems that this is pretty trivial and I should be able to do it through some property of the form. Or is there a simpler way of going about this?
Any help would be appreciated.
You can actually handle it in several different ways. Below are a couple of options.
Option 1:
Set the Record Source property of the form PatientMedication. Set the dropdowns Control Source to PatientID and MedicationID. Then make sure that the required property of PatientID and MedicationID in the PatientMedication table is set to Yes. Then when a user selects a value for the drop downs the record will be added to the database. This assumes that the ID fields data type is set as AutoNumber.
Option 2:
Don't set the Record Source property of the form to PatientMedication. Don't set the dropdowns Control Source, leave them unbound. Set the MedicationID dropdown's Name property to txtMedicationID. Set the PatientID dropdown's Name property to txtPatientID. Set the command buttons Name property to cmdInsertRecord. Use the following code for the On Click event of the button:
Private Sub cmdInsertRecord_Click()
If (VBA.Strings.Len(txtPatientID & "") = 0) Then
MsgBox "You must specify a Patient ID before adding the record.", , "ERROR: Missing Information"
Exit Sub
End If
If (VBA.Strings.Len(txtMedicationID & "") = 0) Then
MsgBox "You must specify a Medication ID before adding the record.", , "ERROR: Missing Information"
Exit Sub
End If
DoCmd.SetWarnings False
DoCmd.RunSQL "INSERT INTO PatientMedication (PatientID, MedicationID) Values " & _
"('" & txtPatientID & "', '" & txtMedicationID & "')"
DoCmd.SetWarnings True
End Sub

Access 2002/VBA - how to populate subform from query to allow user to select a row

Consider:
I have a form I need to display payment events for individual clients on. I do not want to display all columns in the payment table, I want user-friendly column names, and I want Access to display a popup form that displays information should the user click on a row of the form (a payment event).
Firstly, I am unsure whether Access 2002 and VBA will allow me to do this. Secondly, I am unsure how to make the individual payment events on the form clickable.
I assume I can do something like:
strSQL = "SELECT payment.payment_id, payment_amount AS Amount, payment_date AS Date" & _
"FROM contact_payment, payment " & _
"WHERE contact_payment.contact_id =" & forms([ContactForm].contact_id & _
"AND payment.payment_id = contact_payment.payment_id"
in order to get the data for the clickable form. Is this the correct way, or is there a better way to achieve this?
You could use the form's DblClick event (or Click event) to open a new form:
Private Sub Form_DblClick(Cancel As Integer)
DoCmd.OpenForm "frmMoreInfo", , , "ID = " & ID
End Sub

Access Visual Basic Code for concatenating multiple fields (text and numbers together)

I have been set with the task of creating a Microsoft Access database to store customer feedback and to generate a printable report when negative feedback is logged.
On my Feedback form where users can log feedback details, I am trying to develop code to concatenate fields taken from the Feedback table (which the form's record source is set to). What I am aiming to do is develop a unique number which is made up of the following fields from the Feedback table:
Company name (this is actually a lookup field in the Feedback table which looks up Company Name in the Company table so is therefore a combo-box on the form - appears as a drop down menu on the form)
Product name
2 digits of the week number
2 digits of the month
2 digits of the year
(These three date items are extracted from a field called Feedback date in the Feedback table).
A sequential number starting from 1 which increments so that if another piece of feedback is logged on the same product by the same company this number then changes to 2 and so on.
Basically, the example I'm wanting to replicate is to look like this:
Company Name_Product Name_0712131
The output of these concatenated fields is meant to be stored in another field in the Feedback table called CF#.
What kind of code should I be writing so that the information I want concatenated gets saved to the database?
There are many different ways to add a record (CurrentDB.Execute({SQL code}), ADO commands, DAO commands, DoCmd.OpenQuery), but I suspect you want to know how to create the expression that you are going to add:
Dim strCustomerRef As String
'Add the Company Name (assumes the name is in the second column)
strCustomerRef = Me.cboYourComboBox.Column(1)
'Add the Product Name (assumes you have a text box bound to the product)
strCustomerRef = strCustomerRef & "_" & Me.txtTheProductNameTextBox
'Add the date info (assumes you have a text box bound to the date)
strCustomerRef = strCustomerRef & "_" & Format(Me.txtFeedbackDate, "wwmmyy")
'Add the sequence number
strCustomerRef = strCustomerRef & "_" & DCount("CustomerRef", "CF#", "[CustomerRef] Like '" & strCustomerRef & "*'") + 1
'Code to append record here
CurrentDB.Execute "INSERT INTO [CF#] ([CustomerRef], [MoreData]) VALUES ('" & strCustomerRef & "', '" & Me.txtMoreData & "')

How do I use a Checkbox on a form to add a record into a subform in Microsoft Office Access?

I have a database for a carpet company. I have a form which enables the user to make a quote, including choosing the customer, etc. There is a also subform dealing with the products and extras, with quantities and unit prices. To state whether the user requires fitting there is a checkbox. When ticked I would like fitting to be added in the subform as one of the products. Products are normally manually chosen using a dropdown.
Important properties are:
Form name: Orders
Subform name: Order Details Subform
Checkbox name: Fitting
Field name for products: Product ID
Subform linked to table: Order Details
Form linked to table: Orders
I'm assuming VBA is needed, or the macro builder.
Anyway thanks in advance!!
I think the easiest way is to use an append query.
If Me.Fitting Then
strSQL="INSERT INTO [Order Details] (ProductID,OtherTextField) Values ("
& Me.ProductID & ",'" & Me.OtherTextField & "')"
CurrentDB.Execute strSQL, dbFailOnError
Me.[Subform control name here].Form.Requery
End If
On the check box control, you are going to add an [Event Procedure] on the After Update event for the checkbox (see the properties window). This will stub out the VBA code, click on the ellipsis ("...") to get to the VBA code.
You can use Remou's code (after a fashion) to insert the new Product:
If Me.Fitting Then
strSQL="INSERT INTO [Order Details] (ProductID,OtherTextField) " & _
"Values (" & _
Me.ProductID & ",'" & Me.OtherTextField & "')"
CurrentDB.Execute strSQL, dbFailOnError
Me.[Subform control name here].Form.Requery
End If
'[code not tested]
However, you probably also want to check that the Product doesn't already exist in for the Order (does your business rules allow for multiple fittings to be scheduled), and you might also want to allow the Fitting product to be removed when it is unchecked - you could do that with an else condition on the if before the "end if":
if 'blah
'blah blah
else
strSQL="Delete [Order Details] " & _
"where ProductID = " & Me.ProductID & " " & _
"and OtherTextField = 'fitting' "
CurrentDB.Execute strSQL, dbFailOnError
Me.[Subform control name here].Form.Requery
end if
'[code not tested]
You will also have to hack your Products sub form so that if you delete the Fitting product from it, you update the check box (or so that you can't delete Fittings that way).
Then again maybe you don't want to use a check box, and just have the fitting as being another drop down option, as the other products are. You could always make sure it's auto-populated into [Order Details] whenever a new Order is created so it can't be forgotten. This would be more consistent with the rest of the product selection user interface.
This is the no code solution:
Get rid of the Fitting check box. Make fitting a product and add it like all the rest. If you want to know if an order requires a fitting (I'm guessing that's why you have the checkbox.), you can create a query to see if fitting is one of the products on your reports/invoices.