I'm having some trouble updating my table in access through the following code:
Update = "UPDATE formation " & _
"SET AREA = '" & Me.AREA & "', " & _
"TYPE = '" & Me.TYPE & "', " & _
"TEAM = '" & Me.TEAM & "', " & _
"PRIORITY = '" & Me.PRIORITY & "', " & _
"PROCESS = '" & Me.PROCESSO & "', " & _
"NUMBER = " & Me.NumForm.Value & "', " & _
"SUPERVISOR = '" & Me.SUPERVISOR & "', " & _
"Cc = '" & Me.mailCc & "', " & _
"STATUS = 'SUBMITED', " & _
"USER_UPDATE = '" & newFormationUser & "', " & _
"DATA_STATUS_NOW = '" & Now() & "' " & _
"WHERE ID = " & Str(NewFormationID)
DoCmd.SetWarnings False
DoCmd.RunSQL Update
DoCmd.SetWarnings True
NumForm is a ComboBox of numbers 1 to 15.
I've tried to redo query, redo code, remake table with no luck in solving.
Read over and over again to find errors in typo or even in code.
Can you guys help me?
Thank you,
Diogo
There are many things wrong with that statement, but they can all be fixed using parametrization.
First, the missed quote, everyone saw that.
Second, you're setting a column equal to Now(), but not using the proper date formatting, and not using date delimiters (#).
Third, you're using apostrophes to delimit strings, but not testing if the strings themselves contain apostrophes, inviting unpredictable and hard to diagnose errors.
Also, Number is a keyword, that should be enclosed in [] brackets.
You should use parametrization, then most of these errors can't occur:
Dim qd As DAO.QueryDef
Set qd = CurrentDb.CreateQueryDef("", "UPDATE formation " & _
"SET AREA = ?, " & _
"TYPE = ?, " & _
"TEAM = ?, " & _
"PRIORITY = ?, " & _
"PROCESS = ?, " & _
"[NUMBER] = ?, " & _
"SUPERVISOR = ?, " & _
"Cc = ?, " & _
"STATUS = 'SUBMITED', " & _
"USER_UPDATE = ?, " & _
"DATA_STATUS_NOW = ? " & _
"WHERE ID = ?")
qd.Parameters(0) = Me.AREA
qd.Parameters(1) = Me.TYPE
qd.Parameters(2) = Me.TEAM
qd.Parameters(3) = Me.PRIORITY
qd.Parameters(4) = Me.PROCESSO
qd.Parameters(5) = Me.NumForm.Value
qd.Parameters(6) = Me.SUPERVISOR
qd.Parameters(7) = Me.mailCc
qd.Parameters(8) = newFormationUser
qd.Parameters(9) = Now()
qd.Parameters(10) = NewFormationID
qd.Execute
Related
I have 3 combobox to filter data, then i want to open in command button to print preview..
Problems I have if i used 2 combobox it works but when i used three combobox the report is blank...there's any problems with the code?? here's the code i used :
Dim strWhereCondition As String
strWhereCondition = "[month] = '" & Me.cbmonth.Value _
& "' and [Works] = '" & Me.cbwork.Value _
& "' and [Works] = '" & Me.cbwork2.Value & "'"
Debug.Print strWhereCondition
DoCmd.OpenReport "Month List", View:=acViewPreview, _
WhereCondition:=strWhereCondition
and the requery for my form
SELECT *
FROM MyTable
WHERE (month = Forms!nameForm!cbmonth
OR Forms!MeForm!cbwork IS NULL)
And (works = Forms!nameForm!cbwork
OR Forms!nameForm!cbwork IS NULL)
AND (works = Forms!nameForm!cbwork2
OR Forms!nameForm!cbwork2 IS NULL);
can anyone help?
Month is a number, so try:
strWhereCondition = "[month] = " & Me.cbmonth.Value _
& " and [Works] = '" & Me.cbwork.Value _
& "' and [Works] = '" & Me.cbwork2.Value & "'"
Edit: Month is text.
However, [Work] is supposed to match two potentially different values:
& "' and [Works] = '" & Me.cbwork.Value _
& "' and [Works] = '" & Me.cbwork2.Value & "'"
Should most likely be:
& "' and [Works] = '" & Me.cbwork.Value _
& "' and [SomeOtherField] = '" & Me.cbwork2.Value & "'"
I have created a table where I'm saving attachments(in external folder) and file paths in the table. When I'm trying to update existing attachment with another, it does not work. Please see below "Add file" code and "Update button" code.
Private Sub cmAdd_Click()
On Error Resume Next
Dim strLokacioni As String
Dim strSQL As String
strLokacioni = "C:\Users\HSE\Desktop\datas\" & getFileName(Me.path.Value)
strSQL = "INSERT INTO tbl_tracker(path, filename, IncNo, PATS, SAP, First, Last, IncDate, Description, Location, OshaType, IncType, RootCause,Inspector, Surfaces, WeatherCon, WorkRelated, IncTime)" & _
"VALUES ( '" & strLokacioni & "', '" & Me.path.Value & "', '" & Me.txtInc & "', '" & Me.txtPATS & "', '" & Me.txtSAP & "', '" & Me.txtFirst & "', '" & Me.txtLast & "', '" & Me.txtDate & "', '" & Me.txtDesc & "', '" & Me.cmbLoc & "', '" & Me.cmbOsha & "', '" & Me.cmbType & "', '" & Me.txtCause & "', '" & Me.cmbInsp & "', '" & Me.cmbSur & "', '" & Me.cmbWcon & "', '" & Me.cmbRelated & "', '" & Me.txtTime & "')"
CurrentDb.Execute (strSQL)
MsgBox "Record Added", vbInformation, "Information"
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
fso.CopyFile Me.path.Value, strLokacioni
Set fso = Nothing
Me.tbl_tracker_subform.Form.Requery
End Sub
' Below is update button code
Private Sub Command88_Click()
'On Error Resume Next
Dim strLokacioni As String: strLokacioni = "C:\Users\HSE\Desktop\datas\" & getFileName(Me.path.Value)
Me.path = strLokacioni
CurrentDb.Execute "UPDATE tbl_tracker " & _
" SET IncNo = " & Me.txtInc & _
", path = '" & strLokacioni & "'" & _
", filename = '" & Me.filename & "'" & _
", PATS = '" & Me.txtPATS & "'" & _
", SAP = '" & Me.txtSAP & "'" & _
", First = '" & Me.txtFirst & "'" & _
", Last = '" & Me.txtLast & "'" & _
", IncDate = '" & Me.txtDate & "'" & _
", Location = '" & Me.cmbLoc & "'" & _
", Description = '" & Me.txtDesc & "'" & _
", OshaType = '" & Me.cmbOsha & "'" & _
", Inctype = '" & Me.cmbType & "'" & _
", RootCause = '" & Me.txtCause & "'" & _
", Inspector = '" & Me.cmbInsp & "'" & _
", Surfaces = '" & Me.cmbSur & "'" & _
", WeatherCon = '" & Me.cmbWcon & "'" & _
", WorkRelated = '" & Me.cmbRelated & "'" & _
", IncTime = '" & Me.txtTime & "'" & _
" WHERE IncNo = " & Me.txtInc.Tag
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
fso.CopyFile Me.path.Value, strLokacioni
Set fso = Nothing
MsgBox "Record Updated", vbInformation, "Information"
Me.tbl_tracker_subform.Form.Requery
End sub
And the the value Me.path.Value at the start of Command88_click is coming from :
Public Function getFileName(ByVal strPath As String) As String
If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
getFileName = getFileName(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
End If
End Function
Private Sub cbdBrowse_Click()
On Error Resume Next
Dim f As Object
Set f = Application.FileDialog(msoFileDialogFilePicker)
f.AllowMultiSelect = False
f.Show
Me.path.Value = f.SelectedItems(1)
End Sub
When I use update queries like you have here, I would always use the following syntax.
dim db as database
set db = currentDb
db.execute "UPDATE...."
would you require the same? Or have I been going about this a long way.
Also, I would have left a comment as this may not be the answer. Unfortunately, I cant due to rep<50
How I can prevent duplicate values to not insert into the table. I have created a code to INSERT, UPDATE and DELETE and I want to display a MsgBox that there is a duplicate value and to cancel it. Thanks. Below you have the code:
Private Sub Command12_Click()
If Me.emID.Tag & "" = "" Then
If (IsNull(Me.emID) Or (Me.emID = "") Or IsNull(Me.emFirst) Or (Me.emFirst = "") Or IsNull(Me.emLast) Or (Me.emLast = "")) Then
Me.emID.BorderColor = vbRed
Me.emFirst.BorderColor = vbRed
Me.emLast.BorderColor = vbRed
MsgBox "Please fill required fields", vbInformation, "Information"
Exit Sub
End If
CurrentDb.Execute "INSERT INTO tblEmployees(emID, first, last, gender, phone, mobphone, city, state, zip, adress, email, comment)" & _
"VALUES ('" & Me.emID & "', '" & Me.emFirst & "', '" & Me.emLast & "', '" & Me.emGender & "', '" & Me.emPhone & "', '" & Me.emMob & "', '" & Me.emCity & "', '" & Me.emState & "', '" & Me.emZip & "', '" & Me.emAdress & "', '" & Me.emEmail & "', '" & Me.emComment & "')"
MsgBox "Record Added", vbInformation, "information"
Else
CurrentDb.Execute "UPDATE tblEmployees " & _
"SET emiD =" & Me.emID & _
", first ='" & Me.emFirst & "'" & _
", last = '" & Me.emLast & "'" & _
", gender ='" & Me.emGender & "'" & _
", phone = '" & Me.emPhone & "'" & _
", mobphone ='" & Me.emMob & "'" & _
", city ='" & Me.emCity & "'" & _
", state ='" & Me.emState & "'" & _
", zip ='" & Me.emZip & "'" & _
", adress ='" & Me.emAdress & "'" & _
", email ='" & Me.emEmail & "'" & _
", comment ='" & Me.emComment & "'" & _
"WHERE emID =" & Me.emID.Tag
MsgBox "Updated!", vbInformation, "Information"
End If
Me.tblEmployees_subform.Form.Requery
End Sub
It sounds like you'd like to update an employee if one exists for the given ID otherwise you'd like to add a new employee. You can prevent adding duplicate employees by first trying to update an employee record with the given ID and if no records were updated only then do you add a new employee record.
Private Sub Command12_Click()
If (IsNull(Me.emID) Or (Me.emID = "") Or IsNull(Me.emFirst) Or (Me.emFirst = "") Or IsNull(Me.emLast) Or (Me.emLast = "")) Then
Me.emID.BorderColor = vbRed
Me.emFirst.BorderColor = vbRed
Me.emLast.BorderColor = vbRed
MsgBox "Please fill required fields", vbInformation, "Information"
Exit Sub
End If
' You must set CurrentDb to a variable otherwise the RecordsAffected
' property used later will be incorrect.
Dim db As DAO.Database
Set db = CurrentDb
' First try to update an existing employee.
db.Execute _
"UPDATE tblEmployees " & _
"SET first ='" & Me.emFirst & "', " & _
"last = '" & Me.emLast & "', " & _
"gender ='" & Me.emGender & "', " & _
"phone = '" & Me.emPhone & "', " & _
"mobphone ='" & Me.emMob & "', " & _
"city ='" & Me.emCity & "', " & _
"state ='" & Me.emState & "', " & _
"zip ='" & Me.emZip & "', " & _
"adress ='" & Me.emAdress & "', " & _
"email ='" & Me.emEmail & "', " & _
"comment ='" & Me.emComment & "'" & _
"WHERE emID =" & Me.emID.Tag & ";"
' If no records were affected by update then add a new employee.
If db.RecordsAffected = 0 Then
db.Execute _
"INSERT INTO tblEmployees(emID, first, last, gender, phone, mobphone, city, state, zip, adress, email, comment) " & _
"VALUES ('" & Me.emID & "', '" & Me.emFirst & "', '" & Me.emLast & "', '" & Me.emGender & "', '" & Me.emPhone & "', '" & Me.emMob & "', '" & Me.emCity & "', '" & Me.emState & "', '" & Me.emZip & "', '" & Me.emAdress & "', '" & Me.emEmail & "', '" & Me.emComment & "');"
MsgBox "Record Added", vbInformation, "Information"
Else
MsgBox "Updated!", vbInformation, "Information"
End If
Me.tblEmployees_subform.Form.Requery
End Sub
Note: In the update query I removed the update to the emID field since that is what the query is based on (in the WHERE clause). If the emID field is changing you won't be able to use the new emID value to find an employee record with the old emID value.
If you never want any duplicates I would also suggest that you add constraints to your database table to prevent duplicates, as suggested by Daniel Cook. I would also suggest looking into using parameterized queries instead of building SQL strings in VBA.
You can change your SQL to use IF EXISTS condition and insert only if the records does not already exists.
Your SQL may look like:
IF NOT EXISTS
(
SELECT ......
)
BEGIN
INSERT INTO tblEmployees ......<insert since employee does not exists>
END
I have a form with 2 embedded subforms.
The on-click event on subform_1 sets the recordsource of subform_2 referencing 5 attrs from the selected subform_1 record (all TEXT fields).
strSQL = "SELECT Table_1.* FROM Table_1 " & _
"WHERE (((Table_1.Attr_A)= '" & Forms![mainform]![subform_1]![attr1] & "') " & _
"AND ((Table_1.Attr_B) = '" & Forms![mainform]![subform_1]![attr2] & "') " & _
"AND ((Table_1.Attr_C) = '" & Forms![mainform]![subform_1]![attr3] & "') " & _
"AND ((Table_1.Attr_D) = '" & Forms![mainform]![subform_1]![attr4] & "') " & _
"AND ((Table_1.Attr_E) = '" & Forms![mainform]![subform_1]![attr5] & "'));"
Forms![mainform]![subform_2].Form.RecordSource = strSQL
My issue is that some records may have a NULL value among the 5 required attrs, which is a valid condition. The surrounding '' when the subform_1 value is NULL is resulting in (0) records in the collection.
Any suggestions to effectively handle the NULL condition in subform_1?
If you were considering only Table_1.Attr_A, I think you're saying you want this ...
"SELECT t1.* FROM Table_1 AS t1 " & _
"WHERE (t1.Attr_A & '') = '" & Forms![mainform]![subform_1]![attr1] & "'"
If that is correct, add an AND for the next condition based on Attr_B.
"SELECT t1.* FROM Table_1 AS t1 " & _
"WHERE " & _
"(t1.Attr_A & '') = '" & Forms![mainform]![subform_1]![attr1] & "'" & _
" AND (t1.Attr_B & '') = '" & Forms![mainform]![subform_1]![attr2] & "'"
And continue from there by adding the remaining conditions.
I believe the Nz function can also be of use:
"SELECT t1.* FROM Table_1 AS t1 " & _
"WHERE Nz(t1.Attr_A) = '" & Forms![mainform]![subform_1]![attr1] & "'"
The below is in my control source and works:
=IIf(Forms!GARF!GARFsubForm![finished_good_#]<>"",DLookUp("[CustomerSKU]","ItemCustomerSKU","ItemNumber = '" & Forms!GARF!GARFsubForm![finished_good_#] & "' AND Customer = '" & Forms!GARF!customer & "' AND Company = '" & Forms!GARF!company & "' AND MarketingSeason = '" & DLookUp("[Code]","IDtoCode","ID = " & Forms!GARF!season_id) & "' AND Season = " & Forms!GARF!GARFyear),"")
I would like to assign it to another control source through VBA code like such:
Forms![GARF]![GARFsubForm]![SKU].ControlSource = (the above code)
Forms![GARF]![GARFsubForm]![SKU] is a column in a datasheet.
UPDATE:
With Remou's help I was able to come up with the below working solution:
The code is on the Form_Load event:
Forms![GARF]![GARFsubForm]![SKU].ControlSource =
"=IIf(Forms!GARF!GARFsubForm![finished_good_#]<>'',"
& "DLookUp(""[CustomerSKU]"",""ItemCustomerSKU"",""ItemNumber = '""
& Forms!GARF!GARFsubForm![finished_good_#] & ""' AND Customer = '" _
& Forms!GARF!customer & "' AND Company = '" _
& Forms!GARF!company & "' AND Season = " & Forms!GARF!GARFyear _
& " AND MarketingSeason = '"
& DLookup("[Code]", "IDtoCode", "ID = " & Forms!GARF!season_id) & "'"")" & ",'')"
There are a few problems. This is what is returned by your string (broken into lines for clarity):
=IIf(Forms!GARF!GARFsubForm![finished_good_#]<>"",
DLookUp([CustomerSKU],ItemCustomerSKU,"ItemNumber = '"
& Forms!GARF!GARFsubForm![finished_good_#]
& " ' AND Customer = '" & Forms!GARF!customer
& "' AND Company = '" & Forms!GARF!company
& "' AND MarketingSeason = '" & DLookUp([Code],IDtoCode,"ID = "
& Forms!GARF!season_id) & "' AND Season = " & Forms!GARF!GARFyear),"")
As you can see, these two are not quoted and they need to be:
DLookUp([CustomerSKU],ItemCustomerSKU,
There is an extra space here:
& " ' AND Customer = '" & Forms!GARF!customer
Is finished_good_# text similarly season_id?
It is often possible to use single quote ' instead of "", especially if you escape any occurrence of ' in the text with two ' eg ='O''Reilly'
EDIT
You are doing this in code, so it should be possible to make life easier, for example:
A = DLookup("[Code]", "IDtoCode", "ID = " & Forms!GARF!season_id)
B = "DLookUp(""[CustomerSKU]"",""ItemCustomerSKU"",""ItemNumber = '" _
& Forms!GARF!GARFsubForm![finished_good_#] & "' AND Customer = '" _
& Forms!GARF!customer & "' AND Company = '" _
& Forms!GARF!company & "' AND Season = " & Forms!GARF!GARFyear _
& " AND MarketingSeason = '" & A & "'"")"
s = "=IIf(Forms!GARF!GARFsubForm![finished_good_#]<>''," & c & ",'')"
Debug.Print s