I am planning to search and update records which matches my criteria in my table through a form.
I want my code to search for OrderNo and OrderNoItem ( For each orderno I have multiple OrderNoItems like 10,20,30... in my table) when there is a match I want to update the customer name(Text18.Value) from my Form.
I have the following code. For some reason it is just updating only the first record. For example when I input Text25.Value = 12345, Text27.Value = 20 and Text49.Value = 40, it is updating the customer name only for the rows with 12345 and 20. Can any one help??
Set logDB1 = CurrentDb()
Set logRS1 = logDB1.OpenRecordset("Log")
For i = Text27.Value To Text49.Value Step 10
Do Until logRS1.EOF
If (logRS1![OrderNo] = Text25.Value And logRS1![OrderNoItem] = Text27.Value) Then
logRS1.Edit
logRS1![DTN-#] = Text18.Value
logRS1.Update
End If
logRS1.MoveNext
Loop
Next
Because code is set to do that. That's exactly what the If condition requires. What you should do is open the recordset filtered by OrderNo and the OrderNoItem range then just loop those records.
Set logDB1 = CurrentDb()
Set logRS1 = logDB1.OpenRecordset("SELECT [DTN-#] FROM Log WHERE OrderNo='" & _
Me.Text25 & "' AND Val(OrderNoItem) BETWEEN " & Me.Text27 & " AND " & Me.Text49)
Do Until logRS1.EOF
logRS1.Edit
logRS1![DTN-#] = Me.Text18
logRS1.Update
logRS1.MoveNext
Loop
Or instead of opening and looping recordset, Execute an UPDATE action SQL:
CurrentDb.Execute "UPDATE Log SET [DTN-#]='" & Me.Text18 & _
"' WHERE OrderNo = '" & Me.Text25 & "' AND Val(OrderNoItem) BETWEEN " & Me.Text27 & " AND " & Me.Text49
If OrderNo is a number field, remove the apostrophe delimiters.
Strongly advise not to use punctuation/special characters (underscore is only exception) in naming convention. Better would be DTN_Num.
Related
I'm having issues avoiding a "You must enter a value in the __ field" error message in Access 2016. I have three tables, Tasks, Users, and TaskAssignments, and a split form that looks like:
User Task Assigned?
User1 Task1 True
User1 Task2 False
User1 Task3 True
User2 Task1 False
User2 Task2 False
User2 Task3 True
User3 Task1 True
User3 Task2 True
User3 Task3 True
Each task can have multiple users assigned to it, and each user is assigned to multiple tasks. I want my form to display every possible value, then use a checkbox, so that I can click and add a user to that task. The TaskAssignments table has a primary key and a unique constraint on both TaskID and UserID.
The recordsource for my form is a query:
select x.UserName, x.TaskName, ta.is_assigned
from (select * from Tasks, Users) x
left join TaskAssignments ta on (ta.TaskID = x.TaskID and ta.UserID = x.UserID)
I have an on click event that checks if a record exists in TaskAssignments and either updates or inserts into TaskAssignments. When I debug.print and manually run my queries, they both do what's expected. When I manually insert a record into my TaskAssignments table, my form behaves how I expect. When I need to insert a new record, however, I receive a message stating that I must enter a TaskID in TaskAssignments.
I've tried requerying the form, but I still receive the error message. Why can't it find the record that I just inserted?
Help please?!? Do I need to drastically rethink my approach here?
Here's the VBA:
Private Sub is_assigned_Click()
Dim CurrentUser, AssignmentQuery As String, SelectedUserID, SelectedTaskID As Integer
Dim ShouldInsert, IsAssigned As Boolean
CurrentUser = Environ$("Username")
SelectedUserID = Me.UserID
SelectedTaskID = Me.TaskID
IsAssigned = Me.is_assigned
Dim db As DAO.Database, rs As DAO.Recordset, strSQL As String
Set db = CurrentDb
strSQL = "select UserID, taskID from TaskAssignments where UserID=" & SelectedUserID & " and taskID =" & SelectedTaskID & ";"
Set rs = db.OpenRecordset(strSQL)
If rs.EOF = True Then
ShouldInsert = True
Else: ShouldInsert = False
End If
If ShouldInsert = True Then
AssignmentQuery = "insert into TaskAssignments (UserID, taskID, DateAssignmentUpdated, AssignmentUpdatedBy, is_assigned) values " _
& vbCrLf & "(" & SelectedUserID & "," & SelectedTaskID & ",#" & Now & "#,'" & CurrentUser & "'," & IsAssigned & ");"
ElseIf ShouldInsert = False Then
AssignmentQuery = "update TaskAssignments set UserID=" & SelectedUserID & ", DateAssignmentUpdated=#" & Now & "#, AssignmentUpdatedBy='" & CurrentUser & "',is_assigned=" & IsAssigned _
& vbCrLf & " where taskID = " & SelectedTaskID & " And UserID = " & SelectedUserID & ";"
End If
MsgBox AssignmentQuery
db.Execute (AssignmentQuery)
Forms("Task Assignments").Requery
Set rs = Nothing
Set db = Nothing
End Sub
Edit - here are the queries produced:
Insert
insert into TaskAssignments
(UserID, TaskID, DateAssignmentUpdated, AssignmentUpdatedBy, is_assigned)
values (301,4,Now(),'mylogin',True);
Update
update TaskAssignments
set UserID=270, DateAssignmentUpdated=Now(), AssignmentUpdatedBy='mylogin', is_assigned=False
where TaskID = 1 And UserID = 270;
And a constraint on my TaskAssignments table. Both TaskID and UserID are set as required in my table design (which was my whole goal - I was hoping to avoid adding records to TaskAssignments until the user has actually been assigned to a task).
alter table TaskAssignments add constraint TaskAssignmentsConstraint unique (TaskID, UserID);
Beware of wrong datatypes, each Dim needs its own datatype!
Dim CurrentUser As String, AssignmentQuery As String
Dim SelectedUserID As Long, SelectedTaskID As Long ' don't use 16-bit Integer for ID columns
Dim ShouldInsert As Boolean, IsAssigned As Boolean
To avoid troubles with date/time formatting: the database engine knows Now(), so you can directly use this in the Insert SQL:
AssignmentQuery = "insert into TaskAssignments (UserID, taskID, DateAssignmentUpdated, AssignmentUpdatedBy, is_assigned) values " _
& vbCrLf & "(" & SelectedUserID & "," & SelectedTaskID & ", Now(), '" & CurrentUser & "'," & IsAssigned & ");"
If it still doesn't work, use Debug.Print AssignmentQuery instead of MsgBox and add the actual SQL to your question (Ctrl+G shows the output).
Edit
Re-reading the question and comment, I think the problem is:
You are editing a bound form, and are updating/inserting in the same table the form is based on. That's where the Write conflict on Update comes from, the other error is probably because the bound form is trying to insert a record when you click is_assigned, but can't.
So yes, you need to rethink your approach, at least partially.
One solution is to insert the recordsource into a temp table, and base your form on that. Then the rest of the code will probably work.
It may be over-complicating things, though.
I got this problem trying to update a field that use to be a primary field in my table. When I altered what was considered the primary field I assume access would automatically stop enforcing is not null, but for some reason it didn't.
I fixed it by deleting the field, saving the table recreating the field and saving the table and the problem went away. Of course this wouldn't be an ideal solution if you have data in that table you don't want to lose so you might want to try backing it up first, before you give the solution a try, then reinserting the values.
I have an expenditures subform in Access 2010 that lists the predicted costs associated with the project for each year. Most projects only have one year, but some have more than one. Each cost has a Final checkbox next to it that should be checked when the amount is confirmed, ie. at the end of each year.
It basically looks something like this:
Year | Cost | Final
--------+-----------+--------------------
2017 | $100 | [checked box]
2018 | $200 | [unchecked box]
| | [unchecked box]
I have another field outside the table, FinalCost, that adds up everything in the Cost field. Right now, it fills in the amount from any year which has a checked Final box. That should only be filled when all the Final boxes are checked.
Ex. Right now, it should show nothing even though Final for 2017 is checked. When 2018 is checked, it should show $300. Instead, it shows $100 even though there's still an empty checkbox.
This is the code for this form.
Private Sub Form_AfterUpdate()
Dim rs1, rs2 As Recordset
Dim sql, sql2 As String
sql = "SELECT Sum(Amount) as Final From Expenditures " & _
"Where ProjNo = '" + Me.ProjNo + "' And Final = True Group by ProjNo"
sql2 = "SELECT FinalExpenditure From ActivityCash " & _
"Where ProjNo = '" + Me.ProjNo + "'"
Set rs1 = CurrentDb.OpenRecordset(sql, dbOpenDynaset, dpinconsistent)
Set rs2 = CurrentDb.OpenRecordset(sql2, dbOpenDynaset, dpinconsistent)
If rs1.RecordCount > 0 Then
If rs2.RecordCount > 0 Then
Do While Not rs2.EOF
rs2.Edit
rs2!FinalExpenditure = rs1!Final
rs2.Update
rs2.MoveNext
Loop
End If
End If
rs2.Close
rs1.Close
Set rs1 = Nothing
Set rs2 = Nothing
End Sub
What would be the best way to go about doing this?
EDIT: When the last box is checked, a new row is automatically added with an untoggled checkbox but no information.
Replace the statement beginning with sql = ... with this:
sql = "SELECT SUM(e1.Amount) AS Final " & _
" FROM Expenditures AS e1 " & _
" WHERE NOT EXISTS (SELECT 'x' FROM Expenditures e2 WHERE e2.Final=0 AND e1.ProjNo = e2.ProjNo) " & _
" AND e1.ProjNo = '" & Me.ProjNo & "'"
This query will return data only if there are all expeditures for the project marked as final. As you check for rs1.RecordCount > 0 there will be no update if this query returns no records.
So, before sql, I would verify that all records have True in your Final field.
To do that, let's just return a COUNT() of (any) records that have Final = False, and we can then decide to do what we want.
So, something like,
Dim Test as Integer
test = DCount("*", "YourTableName", "Final = False AND ProjNo = " & Me.ProjNo &"")
If test > 0 Then
'Don't fill the box
Else
'Fill the box, everything is True
'Read through your recordsets or whatever else you need to do
End If
To use a query, we essentially need to replicate the Dcount() functionality.
To do this, we need another Recordset variable, and we need to check the value of the Count() field from our query.
Create a query that mimicks this:
SELECT COUNT(*) As CountTest
FROM YourTable
HAVING Final = False
AND ProjNo = whateverprojectnumberyou'reusing
Save it, and remember that query's name.
Much like the DCount(), we need to make this "check" determine the route of your code.
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("YourQuery'sNameHere")
If rst!CountTest > 0 Then
'They are not all Checked (aka True)
Else
'Supply the value to the FinalCost
End If
Set rst = Nothing
Change this:
sql = "SELECT Sum(Amount) as Final From Expenditures " & _
"Where ProjNo = '" + Me.ProjNo + "' And Final = True Group by ProjNo"
For this:
"SELECT SUM(Amount) - SUM(IIF(Final,1,0)*Amount) as YetToConfirm, SUM(Amount) as Confirmed From Expenditures " & _
"Where ProjNo = '" + Me.ProjNo + "' Group by ProjNo"
rs1 will return two values, the total value if all costs were confirmed in the rs1!Confirmed, and the value yet to confirm in rs1!YetToConfirm
Then here:
Do While Not rs2.EOF
rs2.Edit
rs2!FinalExpenditure = rs1!Final
rs2.Update
rs2.MoveNext
Loop
change it to:
Do While Not rs2.EOF
rs2.Edit
rs2!FinalExpenditure = Iif(rs1!YetToConfirm = 0, rs1!Confirmed, 0)
rs2.Update
rs2.MoveNext
Loop
One way to process this would be check using a subquery whether last year(verified using a dmax function) in each project has been checked in the final column, if this is true, get your sum of checked amounts, else dont calculate the sum.
I have modified your sql string to include this and I tested it against your given example to confirm its showing a sum of $300 or nothing.
SQL = ""
SQL = SQL & " SELECT Sum(Amount) as Final From Expenditures "
SQL = SQL & " Where ProjNo = '" & Me.ProjNo & "' And Final = True "
SQL = SQL & " And (SELECT Expenditures.Final FROM Expenditures where year = ( "
SQL = SQL & " DMax('Year','Expenditures','ProjNo= " & Chr(34) & Me.ProjNo & Chr(34) & "'))) = true "
SQL = SQL & " Group by ProjNo "
I am trying to access a specific value (CompanyNr) from the TABLE 1 and store it into a variable. To later use it to access the Company name from TABLE 2
MY TABLE EXAMPLES:
TABLE 1 (Contacts):
ID , CompanyNr , Contact
TABLE 2 (Companies):
CompanyNr , Company
I have a ComboBox for Contacts. And I when I select someone from the ComboBox, I want to automaticly filter out Companies in which the selected Contact works.
I have tried like this:
MY CODE:
CompNr = "SELECT [Contacts].[ID], [Contacts].[CompanyNr] FROM Contacts " & _
"WHERE [Contacts].[ID] = " & ContactNrCombo.Value & " ORDER BY [Contact];"
MsgBox "Company Nr:" & CompNr
sq11 = "SELECT [Companies].[CompanyNr], [Companies].[Company] FROM Companies " & _
"WHERE [Companies].[CompanyNr] = " & CompNr & "ORDER BY [Company]; "
But the MsgBox says:
CompNr = SELECT [Contacts].[ID], [Contacts].[CompanyNr] FROM Contacts WHERE [Contacts].[ID] = 255 ORDER BY [Contact]
Yet I need to get a certain value for CompanyNr (like 50 for example) so that I can use it in my other SQL Statement to filter from TABLE 2.
I am new to SQL statements, I just found the above one as an example on internet and thought I could use it. But it didn`t work well.
Any help would be appreciated
You can try something like the following,
Set con = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
con.Open "Provider=..." 'Your Connectionstring
rs.Open "SELECT [Contacts].[ID], [Contacts].[CompanyNr] FROM Contacts " & _
"WHERE [Contacts].[ID] = " & ContactNrCombo.Value & " ORDER BY [Contact]", con, 1,3
'Assuming there is only one company number per contact
rs.MoveFirst
CompNr = rs.Fields("CompanyNr").Value
rs.Open "SELECT [Companies].[CompanyNr], [Companies].[Company] FROM Companies " & _
"WHERE [Companies].[CompanyNr] = " & CompNr & "ORDER BY [Company]", con, 1,3
'If you want to paste the second sql query in excel use this
Sheets("Sheet1").Range("A1").CopyFromRecordset rs
rs.Close
con.Close
Set con = Nothing
I have encountering a very silly problem. The requirement is to stop the duplicate entry in access table. I am using Vb6. But each time I try I am encountering syntax error.
My code
My flexgrid is populated and refreshed. I am able to insert and select data in another table in same database. But this one is failing
sql_txt1 = "Select SL_No from SpAIReport where DOM ='" & Format(Now, "mm/dd/yyyy") & _
"' and AC-REG ='" & msgDisFlex.TextMatrix(i, 4) & "' and Flt No = '" & msgDisFlex.TextMatrix(i, 6) & "'"
Set rs1 = db.OpenRecordset(sql_txt1)
I am able to update this table, but multiple time same data are getting populated.
The access table structure with the entries are given below
Date_OF_Fly Flt No GMT Weight Airtime Station DOM Data_hrs Filename
7/3/2000 11 03:45:01 5 01:23:40 XXX 01/25/2014 120:10:15 ABCD
Plus, after saving if I want to access it through recordset then it is showing NULL.
The code is:
sql_txt = "select * from SpAIReport where DOM='" & dateDailyReport & "'"
Set rs = db.OpenRecordset(sql_txt)
The dateDailyReport value is 01/25/2014. This value is present in database. Still this query is not working.
Please help.
You probably want to put 'Flt No' and 'AC-REG' in square brackets otherwise they look like two field names:
"' and [AC-REG] ='" & msgDisFlex.TextMatrix(i, 4) & "' and [Flt No] = '" &
I'm having some issues with moving the CurrentDate and LastDayOfMonth to a table in Access for data processing
Dim CD As Date
Dim LDOM As Date
CD = DateSerial(Year(Date), Month(Date), Day(Date))
'Format(Now(), "mm-dd-yyyy")
LDOM = DateSerial(Year(Date), Month(Date) + 1, 0)
'Add Dates
CurrentDb.Execute "UPDATE tblProcess " & _
"SET tblProcess.[CurrentDate] = " & CD
CurrentDb.Execute "UPDATE tblProcess " & _
"SET tblProcess.[DueDate] = " & LDOM
Debug.Print CD
Debug.Print LDOM
Everytime I Debug.Print - either the formula or the variable - it ALWAYS comes out correct.
But what ends up on my table for both fields is "12/30/1899" Can anyone help?
Test simply:
CurrentDb.Execute "UPDATE tblProcess" _
& " SET tblProcess.[CurrentDate] = #" & Format(CD, "yyyy-mm-dd") & "#;"
Your original code uses SQL like this:
UPDATE tblProcess SET tblProcess.[CurrentDate] = 12/03/2013
that is BAD for Access DATETIME field.
Instead we need in final for Accesss SQL string:
UPDATE tblProcess SET tblProcess.[CurrentDate] = #2013-12-03 22:00:13#;
Please stop voting up for such a small contribution, I have not said the last word, for SQL Server, we must use:
UPDATE tblProcess SET CurrentDate = '2013-12-03T22:00:13';
Although Access and SQL Server are both Microsoft of Bill Gates.