I am trying to use an UPDATE query to modify a field in a table from a field in another table.
The query statement I'm using is:
UPDATE Todays_Deliveries SET Remaining = DLookup("Remaining","Current_Delivery","[MP-Ref] = Form![MP-Ref] And [Cat No] ='" & [Cat No] & "'")
WHERE "[MP-Ref] = Form![MP-Ref] And [Cat No] ='" & [Cat No] & "'";
MP-Ref is the delivery reference.
Cat No is the item reference.
Where Todays_Deliveries is a table with the total records related to items coming in from deliveries on a given day. The user selects a delivery using a form which then uses an APPEND query to populate the Current_Delivery table based on the delivery reference. Once the user is finished the Current_Delivery table is cleared using a DELETE query.
Both tables have a Remaining value with the total number of a particular record that still needs to be booked in. The query updates the Todays_Deliveries table when the user modifies the Remaining field of the Current_Delivery on the Current_Delivery form. Everything works fine but any records that aren't in the Current_Delivery table when the query is run are updated to NULL.
Removing the WHERE clause seems to have no impact on the results, which leads me to believe I am not utalising the WHERE clause correctly.
Any help/advice would be greatly appreciated.
Your whole Where clause is enclosed within double-quotes.
That is a bit odd even for Ms Access.
Try this :
UPDATE Todays_Deliveries
SET Remaining = DLookup("Remaining","Current_Delivery","[MP-Ref] = Form![MP-Ref] And [Cat No] ='" & [Cat No] & "'")
WHERE [MP-Ref] = Form![MP-Ref] And [Cat No] = "'" & [Cat No] & "'";
Related
I am using VBA and trying to perform a SQL query to measure how many records exist where a certain column has a prefix of a given string. As I am debugging this process I am left very confused because it seems like there is very little room for error, but I'm still seeing strange behavior. SELECT * FROM [Part Sales Header] WHERE [Quote No] LIKE 'sm82520A' ; finds one record as I'd expect. However, if I change it to SELECT * FROM [Part Sales Header] WHERE [Quote No] LIKE 'sm82520%' ; 0 records are found. By my understanding % should find anything that comes after.
If it is useful, the rest of the VBA code that I am using looks like this:
sSQL = "SELECT * FROM [Part Sales Header] WHERE [Quote No] LIKE 'sm82520A' ;"
Set rst = CurrentDb.OpenRecordset(sSQL)
QuoteNoAmount = rst.RecordCount
If you're using MS Access, the wildcard is *, so it would be
sSQL = "SELECT * FROM [Part Sales Header] WHERE [Quote No] LIKE 'sm82520A*' ;"
I am trying to update a table in MS Access using the following query:
UPDATE [Stock Detail Item]
SET [Stock Detail Item].Total_Payments =
IIF(
IsError(DSum("Payment_Amount", "Principal Payments", "Stock_No='" & [Stock Detail Item].Stock_No & "'")),
CCur(0),
DSum("Payment_Amount", "Principal Payments", "Stock_No='" & [Stock Detail Item].Stock_No & "'")
);
When there are payments for the Stock_No in the Principal Payments table, the query correctly inserts the total payment amount into the table.
But when there are no payments in the Principal Payments table, the IsError function should return True, which means the IIF should return 0 cast to currency.
The problem is, the query is inserting NULL in these instances. This is causing errors later down the line when trying to perform math to the NULL value.
I have tried this with and without casting 0 or 0.00 to the currency data type, with no luck.
Any idea why this returns the correct value when no error is present, and NULL value when there is an error?
You state:
But when there are no payments in the Principal Payments table, the IsError function should return True.
However, per the documentation, when no records match the given criteria or if the domain (table/query) contains no records, the DSum function will return Null, not an error:
If no record satisfies the criteria argument or if domain contains no records, the DSum function returns a Null.
As such, I would suggest changing your code to the following:
update [Stock Detail Item]
set [Stock Detail Item].Total_Payments =
Nz(DSum("Payment_Amount", "Principal Payments", "Stock_No='" & [Stock Detail Item].Stock_No & "'"),0)
This statement makes use of the Nz function, which will return the second supplied argument (which is 0 in the above code) in the event that the first is Null, else the first argument (the result of DSum) is returned.
Alternatively, you could use the IsNull function in place of IsError.
Coworker is completely Access adverse. I can't force him to update a SQL query with a to/from date and customer name. Current query is this:
SELECT [all customers]
FROM [information list]
WHERE
[date] Between [start date YYYYMMDD] and [end date YYYYMMDD]
and [all customers] = ['specific customer']
Group By [all customers] (this prevents duplicate entries or shipping a customer's order between factories counting as a separate order)
This coworker is so access adverse he wants a wysiwyg and a button to press to overwrite [start date YYYYMMDD] [end date YYYYMMDD] ['specific customer']
I can make a form just fine, but I have no idea how to populate the sql query with form answers. Having him copy and paste these three things into my perfectly good, working query is out of the question, as easy as that answer is.
How would i write a macro that can update this query with those answers replacing the three existing items (the two dates and customer ID)?
you concatenate the textbox values to create the sql query string
sql = "SELECT [all customers] FROM [information list]" _
& "WHERE [date] Between ['" & myForm.Textbox1.Text _
& "'] and ['" & myForm.Textbox2.Text _
& "'] and [all customers] = ['" & myForm.Textbox3.Text _
& "'] Group By [all customers]"
adjust the form name and the textbox names to fit your needs
I have a table tblCosts which i display on an msaccess front end which enables users to add new entries as well as update existing ones. The table is structured as below.
ExpenseType Month Year Cost
Hardware June 2017 $500
Software July 2017 $300
Hardware Sept 2017 $150
I have an update and insert queries which work fine when run manually.
However I am having trouble differentiating the condition when to fire the query on the form. For example, if the record exists in the table, it should run the update query, if record does not exist, it should run the insert query.
For example if someone puts in
- Hardware Sept 2017 $120 it should update the 3rd entry from 150 to 120 but if someone puts in
- Furniture Sept 2017 $350 it should recognize that Furniture is not part of the DB and run the insert query. I have the update and insert queries but need help in identifying the condition when to run them.
The Update query I'm using is:
Update tblCosts
set tblCosts.Cost=[Forms]![frmCost]![txtCost]
where tblCosts.ExpenseType = [Forms]![frmCost]![txtExpType]
and tblCosts.Month = [Forms]![frmCost]![txtMonth]
and tblCosts.Year = [Forms]![frmCost]![txtYear]
The Insert query I'm using is:
Insert into tblCosts (ExpenseType , Month, Year, Cost)
Select [Forms]![frmCost]![txtExpType] as Exp1,
[Forms]![frmCost]![txtMonth] as Exp2,
[Forms]![frmCost]![txtYear] as Exp 3,
[Forms]![frmCost]![txtCost] as Exp 4
Need code (VBA or macro) behind a form that determines which action query to run. In VBA something like:
If DCount("*", "tablename", "ExpenseType='" & Me.cbxExpense & "' AND [Month]='" & Me.tbxMonth & "' AND [Year]=" & Me.tbxYear) = 0 Then
CurrentDb.Execute "INSERT INTO tablename (Expense, [Month], [Year], Cost) VALUES ('" & Me.cbxExpense & "', '" & Me.tbxMonth & "', " & Me.tbxYear & ", " & Me.tbxCost & ")"
Else
CurrentDb.Execute "UPDATE tablename SET Cost=" & Me.tbxCost & " WHERE Expense='" & Me.cbxExpense & "' AND [Month]='" & Me.tbxMonth & ", [Year]=" & Me.tbxYear
End If
Probably also want some validation code to make sure all four controls have data before executing queries.
The real trick is figuring out what event to put code into - the Cost AfterUpdate will work as long as the other fields have data entered first, otherwise the validation will fail and user will have to re-enter cost.
Could have code that doesn't make each control available until previous value is entered.
Month and Year are reserved words and should not use reserved words as names for anything.
Would be better to save month numbers instead of month names for sorting purposes.
Why updating a value which really should be a calculated aggregation of transaction records?
I have an access database that I will be using to track orders and to track inventory levels. When I attempt to add the parts on my order form (sbfrmOrderDetails) to my inventory table (tblInventory) my VBA code does not execute as planned.
Please note that I have stripped down the code and the tables to just the relevant information/values. The code posted below does work, just not as intended. I explain in much more detail below.
Form Structure
I created my Order form (frmOrder) as a Single Form. This form is referred to in my later code to determine the order number using the txtOrderID control. When I link my subform, the linked master field is OrderID.
Within this form is my Order Details subform (sbfrmOrderDetails) as a continuous form. Every control is bound, and it is linked to the parent form. The linked child field is OrderID.
Photo 1: This photo may better illustrate my form:
Table Structure
The relevant tables I have are structured like so:
TableName: tblOrders
TableColumns: OrderID
TableName: tblOrderDetails
TableColumns: ID|InvID|Qty|OrderID|DeliveryStatus
TableName: tblInventory
TableColumns: ID|InvID|Qty|OrderID
Intended Action
The action I am trying to take occurs in the subform and is supposed to be isolated to the current record. When the user changes the ComboBox (Combo1 bound control to tblOrderDetails.DeliveryStatus), my VBA code will execute an 'INSERT INTO' SQL string that adds the InvID and the Qty from the current record into the inventory table (tblInventory).
VBA Code for Combo1 AfterUpdate Event (On sbfrmOrderDetails)
Private Sub Combo1_AfterUpdate()
Dim db As DAO.Database
Dim strSQL As String
Set db = CurrentDb
If Me.Combo1.Value = "Delivered" Then
strSQL = "INSERT INTO [tblInventory] ([InvID],[Qty])" _
& "SELECT " & Forms![frmOrder].Form![sbfrmOrderDetails].Form![txtInvID] & " AS InvID," & Forms![frmOrder].Form![sbfrmOrderDetails].Form![txtQty] & " AS Qty " _
& "FROM tblOrderDetails WHERE ((tblOrderDetails.OrderID)=(" & Forms![frmOrder]![txtOrderID] & "));"
Debug.Print strSQL
db.Execute strSQL, dbFailOnError
Else
'Other event
End If
End Sub
Intended Results
When Combo1 (bound control) is changed from null to “Delivered” on record ID #11 only, it is supposed to add a single new record.
Photo 2: Intended Results:
Actual Results
When Combo1 (bound control) is changed from null to “Delivered” on record ID #11 only, it is adding a new record for every record populated in the subform.
Please refer to Photo 2 above to compare the Intended Results to the Actual Results.
You can see that the quantity from records 12 and 13 are transferred over under the InvID from record 11.
Please refer to Photo 1 to view the sample data and also to Photo 2 above to see the Actual Result of the code.
I suspect that since this is a continuous form that has Parent/Child linking, the form is running the VBA code once for every record (instead of one time for the current record).
Can I alter my VBA code to only run this code once on the current record as is intended? I am hoping this is the best approach to complete this task.
The output of Debug.Print strSQL would have been helpful (see How to debug dynamic SQL in VBA ), but it would be something like this:
INSERT INTO tblInventory (InvID, Qty)
SELECT 14 AS InvID, 2 AS Qty
FROM tblOrderDetails
WHERE tblOrderDetails.OrderID = 5
You are inserting two constant values, so you may as well use the INSERT ... VALUES (...) syntax, which by definition only inserts one record:
INSERT INTO tblInventory (InvID, Qty)
VALUES (14, 2)
The reason your statement inserts multiple records is because of WHERE tblOrderDetails.OrderID = 5. Multiple records (all on the subform) satisfy this clause.
You would have to specify the OrderDetails ID instead, to get only one record:
INSERT INTO tblInventory (InvID, Qty)
SELECT 14 AS InvID, 2 AS Qty
FROM tblOrderDetails
WHERE tblOrderDetails.ID = <Forms![frmOrder]![sbfrmOrderDetails].Form![txtID]>
tblOrders.OrderID --> this table has not been referenced in the statement and vba should throw an error
strSQL = "INSERT INTO [tblInventory] ([InvID],[Qty])" _
& "SELECT " & Forms![frmOrder].Form![sbfrmOrderDetails].Form![txtInvID] & " AS InvID," & Forms![frmOrder].Form![sbfrmOrderDetails].Form![txtQty] & " AS Qty " _
& "FROM tblOrderDetails WHERE ((tblOrders.OrderID)=
(" & Forms![frmOrder]![txtOrderID] & "));"
Debug.Print strSQL