Update another table when field is changed - sql

I have a form contains "DateProduced" field. The table bound to it is called "Report".
I try to add after update event to this field and want this event to update "DateProduced" field in Quantity table if ID matches for both.
Me![Text0] displays the ID from Report field
Me![Text4] displays the DateProduced from Report field.
The event code is as below.
Private Sub Text4_AfterUpdate()
Dim strSQL As String
strSQL = "UPDATE Quantity " _
& "SET [DateProduced] = (#" & Me![Text4] & "#) " _
& "WHERE ID = (" & Me![Text0] & ")"
DoCmd.RunSQL strSQL
End Sub
But i can not succeed.

That date format will fail for values where dd/mm can be interchanged for a valid date. It should read:
Private Sub Text4_Exit(Cancel As Integer)
Dim strSQL As String
strSQL = "UPDATE Quantity " _
& "SET [DateProduced] = #" & Format(Me!Text4.Value, "yyyy\/mm\/dd") & "# " _
& "WHERE [ID] = " & Me![Text0].Value & ";"
DoCmd.RunSQL strSQL
End Sub
A note: You should change the names of Text0 etc. to meaningful names.

I made it work with the following code. Thx
Private Sub Text4_Exit(Cancel As Integer)
Dim strSQL As String
strSQL = "UPDATE Quantity " _
& "SET [DateProduced] = #" & Format(Me.Text4.Value, "dd-mm-yyyy") & "#" _
& "WHERE [ID] = (" & Me![Text0] & ");"
DoCmd.RunSQL strSQL
End Sub

Related

How to Pass SQL Parameter to Form Using OpenArgs?

I have a Database (not built by me) that uses 3 separate forms to accomplish 1 thing.
I would instead like to pass a SQL string to the OpenArgs in order to utilize 1 form.
Original Code for form I'd like to utilize:
Private Sub Form_Open(Cancel As Integer)
Dim strSQL As String
If Not IsNull(Me.OpenArgs) Then
strSQL = "SELECT tbl_COMBINED.[First Name] AS [Name Badge], 'P' AS Logo, Format(Now(),""yyyy"") & STOCKHOLDERS MEETING' AS MEETING " _
& "FROM tbl_COMBINED " _
& "GROUP BY tbl_COMBINED.[First Name], 'P', Format(Now(),""yyyy"") & ' STOCKHOLDERS MEETING', " _
& "tbl_COMBINED.ACCOUNT, tbl_COMBINED.Came " _
& "HAVING tbl_COMBINED.ACCOUNT = '" & CStr(Me.OpenArgs) & "' " _
& "AND ((tbl_COMBINED.Came) Is Null Or (tbl_COMBINED.Came)) = 0"
Me.RecordSource = strSQL
End If
End Sub
Each of the other forms is called by using
DoCmd.OpenForm "frm_newmanualnamebadge", "", "",, acNormal
from the Main form and has the SQL string in the row source. I would like to eliminate the row source and utilize the 1 form. I set the string from each button to:
strManuel = "SELECT tbl_manual_name_badge.NAMEBADGE1, tbl_manual_name_badge.MEETING, " _
& "tbl_manual_name_badge.LOGO, tbl_manual_name_badge.Stockerholder " _
& "FROM tbl_manual_name_badge"
DoCmd.OpenForm "frm_newmanualnamebadge", "", "",, acNormal, strManual
Passing the strManual to the form as a SQL string, however, every time I run it I get a "#Name?" in the name field instead of the name entered.
Here is the code I used on the form:
If Not IsNull(Me.OpenArgs) Then
strSQL = "SELECT tbl_COMBINED.[First Name] AS [Name Badge], 'P' AS Logo " _
& "FROM tbl_COMBINED " _
& "GROUP BY tbl_COMBINED.[First Name], 'P', " _
& "tbl_COMBINED.ACCOUNT, tbl_COMBINED.Came " _
& "HAVING tbl_COMBINED.ACCOUNT = '" & CStr(Me.OpenArgs) & "' " _
& "AND ((tbl_COMBINED.Came) Is Null Or (tbl_COMBINED.Came)) = 0"
Me.RecordSource = strSQL
ElseIf IsNull(Me.OpenArgs) Then
strSQL = "SELECT tbl_manual_name_badge.NAMEBADGE1, tbl_manual_name_badge.MEETING, " _
& "tbl_manual_name_badge.LOGO, tbl_manual_name_badge.Stockerholder " _
& "FROM tbl_manual_name_badge"
Me.RecordSource = strSQL
End If
Well, you either pass one value, or you pass the whole sql string.
But, if you passing the WHOLE sql string for the form, then this makes no sense:
If Not IsNull(Me.OpenArgs) Then
strSQL = "SELECT tbl_COMBINED.[First Name] AS [Name Badge], 'P' AS Logo " _
& "FROM tbl_COMBINED " _
& "GROUP BY tbl_COMBINED.[First Name], 'P', " _
& "tbl_COMBINED.ACCOUNT, tbl_COMBINED.Came " _
& "HAVING tbl_COMBINED.ACCOUNT = '" & CStr(Me.OpenArgs) & "' " _
& "AND ((tbl_COMBINED.Came) Is Null Or (tbl_COMBINED.Came)) = 0"
Me.RecordSource = strSQL
I mean, OpenArgs is a WHOLE sel string, and I am VERY sure that ACCOUNT = " some huge sql string" will NEVER work.
So, you would want this:
Dim strSQL As String
If Not IsNull(Me.OpenArgs) Then
strSQL = me.OpenArgs
else
strSQL = "SELECT tbl_manual_name_badge.NAMEBADGE1, tbl_manual_name_badge.MEETING, " _
& "tbl_manual_name_badge.LOGO, tbl_manual_name_badge.Stockerholder " _
& "FROM tbl_manual_name_badge"
End If
Me.RecordSource = strSQL
So, our logic is now:
if passed sql string (openargs), then that becomes our sql
if no open arges, then use the defined sql we have in the on-load

Update SQL MS Access 2010

This is wrecking my brains for 4 hours now,
I have a Table named BreakSked,
and I this button to update the table with the break end time with this sql:
strSQL1 = "UPDATE [BreakSked] SET [BreakSked].[EndTime] = " & _
Me.Text412.Value & " WHERE [BreakSked].AgentName = " & Me.List423.Value _
& " AND [BreakSked].ShiftStatus = '1'"
CurrentDB.Execute strSQL1
Text412 holds the current system time and List423 contains the name of the person.
I'm always getting this
"Run-time error 3075: Syntax Error (missing operator) in query
expression '03:00:00 am'
Any help please?
EDIT: Thanks, now my records are updating. But now its adding another record instead of updating the record at hand. I feel so silly since my program only has two buttons and I can't figure out why this is happening.
Private Sub Form_Load()
DoCmd.GoToRecord , , acNewRec
End Sub
Private Sub Command536_Click()
strSQL1 = "UPDATE BreakSked SET BreakSked.EndTime = '" & Me.Text412.Value & "',BreakSked.Duration = '" & durationz & "' " & vbCrLf & _
"WHERE (([BreakSked].[AgentID]='" & Me.List423.Value & "'));"
CurrentDb.Execute strSQL1
CurrentDb.Close
MsgBox "OK", vbOKOnly, "Added"
End Sub
Private Sub Command520_Click()
strSql = "INSERT INTO BreakSked (ShiftDate,AgentID,StartTime,Status) VALUES ('" & Me.Text373.Value & "', '" & Me.List423.Value & "', '" & Me.Text373.Value & "','" & Me.Page657.Caption & "')"
CurrentDb.Execute strSql
CurrentDb.Close
MsgBox "OK", vbOKOnly, "Added"
End Sub
You wouldn't need to delimit Date/Time and text values if you use a parameter query.
Dim strUpdate As String
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
strUpdate = "PARAMETERS pEndTime DateTime, pAgentName Text ( 255 );" & vbCrLf & _
"UPDATE BreakSked AS b SET b.EndTime = [pEndTime]" & vbCrLf & _
"WHERE b.AgentName = [pAgentName] AND b.ShiftStatus = '1';"
Debug.Print strUpdate ' <- inspect this in Immediate window ...
' Ctrl+g will take you there
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", strUpdate)
qdf.Parameters("pEndTime").Value = Me.Text412.Value
qdf.Parameters("pAgentName").Value = Me.List423.Value
qdf.Execute dbFailOnError
And if you always want to put the current system time into EndTime, you can use the Time() function instead of pulling it from a text box.
'qdf.Parameters("pEndTime").Value = Me.Text412.Value
qdf.Parameters("pEndTime").Value = Time() ' or Now() if you want date and time
However, if that is the case, you could just hard-code the function name into the SQL and dispense with one parameter.
"UPDATE BreakSked AS b SET b.EndTime = Time()" & vbCrLf & _
As I said in my comment you need to wrap date fields in "#" and string fields in escaped double quotes
strSQL1 = "UPDATE [BreakSked] SET [BreakSked].[EndTime] = #" & _
Me.Text412.Value & "# WHERE [BreakSked].AgentName = """ & Me.List423.Value & _
""" AND [BreakSked].ShiftStatus = '1'"

Combobox filtering for listbox output is not working as expected

I have a few controls (Combobox's I call DDL's) that I use as filters for a dynamic query, shown below.
I have a region, division filter - and BCI/BCV/ABC/etc dropdowns.
When I select the region and division, the output list box correctly filters out everything except THOSE region/divisions. Good.
The problem comes in when I use the other DDL's, ABD/BCI/etc... those do not filter out correctly and I think it is with my and/or clauses below.
Can anyone see anything glaring or point me in the right direction to get this so that every control and ddl element filters out the data it is intended for - while keeping it in a format where the SQL itself is part of a string, like in my example?
Private Sub goBtn_Click()
strSQL = "SELECT [account_number], [BCI_Amt], [BCV_Amt],[ABC_Amt], [other_Amt], " & _
"[BCI_Amt]+[BCV_Amt]+[ABC_Amt]+[other_MRC_Amt], Division_Name, Region_Name, " & _
"Tier, Unit_ID, Name, Description_2 " & _
"FROM dbo_ndw_bc_subs " & _
"WHERE DivisionDDL = [Division_Name] and RegionDDL = [Region_Name] " & _
" and ( [BCI_Ind] = CheckBCI.value or [BCV_Ind] = CheckBCV.value or [ABC_Ind] = CheckABC.value " & _
" or BCIServiceDDL = [Tier]" & _
" or BCVServiceDDL = [Description_2]" & _
" or ABCServiceDDL = [Unit_ID] )" & _
"ORDER BY 6 asc"
Me.output1.RowSource = strSQL
End Sub
One of the combo box DDL control codes. There are check boxes that make the combo box visible or not visible.
Private Sub CheckBCV_Click()
If Me.CheckBCV = vbTrue Then
Me.BCVServiceDDL.Visible = True
Me.BCVServiceDDL = "Select:"
strSQL = "SELECT Distinct subs.[Description_2] FROM dbo_ndw_bc_subs "
Me.BCVServiceDDL.RowSource = strSQL
Me.BCVServiceDDL.Requery
Else
Me.BCVServiceDDL.Visible = False
Me.BCVServiceDDL = ""
End If
End Sub
Edit: Added additional code to the first code block for context, and updated some comments.
To reiterate the point of my question - Since some of the DDL's work as expected while the others do not. Is it in the AND/OR section where I have a problem - or am I forced to do an IF/IIF statement in the select. (And if I do this IF solution - how would that be incorporated into a string the way I have it now, I have not seen an example of this in my research on a resolution).
I think your top code sample should read more like this:
Private Sub goBtn_Click()
Dim strSQL As String
Dim strWhere As String
Dim strOp As String
strSQL = "SELECT [account_number], [BCI_Amt], [BCV_Amt],[ABC_Amt], [other_Amt], " & _
"[BCI_Amt]+[BCV_Amt]+[ABC_Amt]+[other_MRC_Amt], Division_Name, Region_Name, " & _
"Tier, Unit_ID, Name, Description_2 " & _
"FROM dbo_ndw_bc_subs "
strWhere = ""
strOp = ""
If Not IsNull(Me.DivisionDDL.Value) Then
strWhere = strWhere & strOp & "(Division_Name = """ & Me.DivisionDDL.Value & """)"
strOp = " And "
End If
If Not IsNull(Me.RegionDDL.Value) Then
strWhere = strWhere & strOp & "(Region_Name = """ & Me.RegionDDL.Value & """)"
strOp = " And "
End If
If Me.CheckBCI.Value Then
strWhere = strWhere & strOp & "(Tier = """ & Me.BCIServiceDDL.Value & """)"
strOp = " And "
End If
If Me.CheckBCV.Value Then
strWhere = strWhere & strOp & "(Description_2 = """ & Me.BCVServiceDDL.Value & """)"
strOp = " And "
End If
If Me.CheckABC.Value Then
strWhere = strWhere & strOp & "(Unit_ID = """ & Me.ABCServiceDDL.Value & """)"
strOp = " And "
End If
If Len(strWhere) > 0 then
strSQL = strSQL & " WHERE " & strWhere
End If
strSQL = strSQL & " ORDER BY 6 asc"
Me.output1.RowSource = strSQL
End Sub
This is wordier, but much closer to correct. P.S. I guessed that all values are strings. If not remove the quoting around non-string values.

Update function with case SQL and VBA

I want to try to have a SQL function to update mine table and put a date in the column, I'm using a update function with a case, but I get the error that an operator is missing.
but I can't find the error, does anybody know where it is?
Public Function Add_date( _
ByVal startDate As String, _
ByVal strTableName As String, _
ByVal strFieldName As String, _
ByVal strNummeringField As String) _
As Boolean
Dim strSql As String
strSql = "ALTER TABLE " & strTableName & " ADD " & strFieldName & " date"
DoCmd.RunSQL strSql
strSql = "UPDATE " & strTableName & " SET " & strFieldName & " = CASE WHEN " & strNummeringField & " < 25 THEN '23-07-1991' ELSE '01-01-01' END"
MsgBox strSql
DoCmd.RunSQL strSql
End Function
Jet/ACE (the MS Access db engine) does not support CASE...WHEN. The equivalent for ternary operations is IIF (immediate if). Also, date delimiters are #, not '. Try this instead:
strSql = " UPDATE " & strTableName & _
" SET " & strFieldName & " = " & _
" IIf(" & strNummeringField & " < 25, #23-07-1991#, #01-01-01#)"
Also, you may run into trouble formatting your dates as DD-MM-YYYY, regardless of your regional settings. See International Dates in Access for more information.
One possibility is that the strings representing the table and column name contain invalid characters. Try enclosing them in square brackets:
strSql = "ALTER TABLE [" & strTableName & "] ADD [" & strFieldName & "] date"
DoCmd.RunSQL strSql
strSql = "UPDATE [" & strTableName & "] SET [" & strFieldName & "] = CASE WHEN [" & strNummeringField & "] < 25 THEN '23-07-1991' ELSE '01-01-01' END"

Using form combo boxes apply a filter to a query

I think I am close to this one, but can't work out the filtering process.
tblIndex(PrimaryCat,SubCat,UserID,Year)
tblResults(SubCat,UserID)
My Form has two combo boxes and a button. ComboBox1 has tblIndex.PrimaryCat values and ComboBox2 has tblIndexYear values.
What I want is when the command button in the form is pressed, tblResults opens showing the list of SubCat and UserID values when the combobox values are used as a filter on tblIndex.
Does this make sense?
I have the recordsource of the form set to tblResults. I'm using this, just need to add in filtering somehow:
Private Sub cmdGo_Click()
Dim strSQL As String
strSQL = "SELECT SubCat, UserID " & _
"FROM tblIndex " & _
"WHERE PrimaryCat = [strCat] AND Year = [strYear] " & _
"GROUP BY SubCat, UserID"
DoCmd.OpenQuery "strSQL"
End Sub
EDIT:
I'm not sure if I am allowed to answer my own question but I worked out a solution. I >used INTO to put the results into a temp table I can further manipulate using:
Private Sub cmdGo_Click()
Dim strSQL As String
strSQL = "SELECT SubCat, UserID INTO tblTemp " & _
"FROM tblIndex " & _
"WHERE PrimaryCat = '" & cboPrimaryCat.Value & "' AND Year = '" & >cboYear.Value & _
"' GROUP BY SubCat, UserID"
DoCmd.RunSQL strSQL
End Sub
Worked it out. Can't run SQL without first storing it in a query. Solution is:
Private Sub cmdGo_Click()
Dim qdfCurr As DAO.QueryDef
Dim strSQL As String
strSQL = "SELECT SubCat, UserID " & _
"FROM tblIndex " & _
"WHERE PrimaryCat = '" & strCat.Value & "' AND Year = '" & strYear.Value & _
"' GROUP BY SubCat, UserID"
On Error Resume Next
Set qdfCurr = CurrentDb.QueryDefs("TempQuery")
If Err.Number = 3265 Then
Set qdfCurr = CurrentDb.CreateQueryDef("TempQuery")
End If
qdfCurr.SQL = strSQL
DoCmd.OpenQuery "TempQuery"
End Sub
I think that this sould work. Working with temp tables is more complicated. Imagine that you have 50 queries with their corresponding temp table!
Private Sub cmdGo_Click()
Dim strSQL As String
strSQL = "SELECT SubCat, UserID " & _
"FROM tblIndex " & _
"WHERE PrimaryCat = " & Forms!FormName![strCat] & " AND Year = " & Forms!FormName![strYear] " " & _
"GROUP BY SubCat, UserID"
DoCmd.OpenQuery strSQL
End Sub