MSAccess: Null vs '' - driving me crazy - ms-access

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] & "'"

Related

Syntax error in UPDATE Statement can't find the solution

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

Open Report Use Three Combobox Filter

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 & "'"

DSum with tempvars returning error

I have some VBA code that sets a TempVar:
TempVars!ThisQtr = quarter
TempVars!LastQtr = lastQuarter
TempVars!LastYr = lastYear
TempVars!ThisYr = currentYear
Great! I know that it does set it as I have checked multiple times.
now my problem:
I'm trying to use this in a query
DSum("[SumBase]","CompareUnionQuery","[AU] = '" & [AU] & "' AND [GRP_ID] = " & [GRP_ID] & " AND [ACCOUNT] = '" & [ACCOUNT] & "'" & " AND [Fiscal_Year] = " & [TempVars]![ThisYr] & " AND [QTR]= " & [TempVars]![ThisQtr])
which this does work when I change out the TempVars with values. Can anyone help me with this?
I have tried to put a single quote around them and that doesn't work.
this expression does work:
DSum("[SumBase]","CompareUnionQuery","[AU] = '" & [AU] & "' AND [GRP_ID] = " & [GRP_ID] & " AND [ACCOUNT] = '" & [ACCOUNT] & "'" & " AND [Fiscal_Year] = 2015 AND [QTR]= '3'")
Compare the last pieces of your DSum expressions ...
AND [QTR]= '3'")
AND [QTR]= " & [TempVars]![ThisQtr])
You reported #1 works and #2 triggers the "Data type mismatch" error. So add single quotes before and after the TempVar value ...
AND [QTR]= '" & [TempVars]![ThisQtr] & "'")

Access VBA/Prevent duplicate values

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

VBA: Syntax error when passing numeric value to a field using UPDATE

Here is my code
Dim orderid As Long
orderid = DMax("Number", "Orders", "") + 1
DoCmd.RunSQL "Update Order_temp " _
& "Set Number = " & orderid & ", Name = '" & Me.Textbox & "' " _
& "WHERE (Name = '*')"
It works fine if it's only like this
Dim orderid As Long
orderid = DMax("Number", "Orders", "") + 1
DoCmd.RunSQL "Update Order_temp " _
& "Set Name = '" & Me.Textbox & "' " _
& "WHERE (Name = '*')"
Thank you in advance.
try using square brackets when referencing fields of a table like so :
DoCmd.RunSQL "Update [Order_temp] " _
& "Set [Number] = " & orderid & ", [Name] = '" & Me.Textbox & "' " _
& "WHERE ([Name] = '*')"
It will help avoiding conflicts on reserved words like Number.
Also I would edit a bit the other line as well :
orderid = Nz(DMax("Number", "Orders", ""),0) + 1
In order to avoid a Null exception.