DCount returning 0 but should return 1 - ms-access

I have the following DCount code in my VBA:
If DCount("*", "tbl2Employee_Order", _
"[Operation_Date] = #" & Operation_Date & _
"# AND [Employee_ID]= " & Employee_ID & _
" AND [Order_ID] = " & Order_ID & _
" AND [Model_Operation_ID] = " & MO_ID) = 0 Then
'some code to insert into tbl2Employee_Order
Else
'some code to update the existing record
End If
However, my DCount always returns 0, even if the record already exists. The following:
Debug.Print Operation_Date, Employee_ID, Order_ID, MO_ID, DCount("*", "tbl2Employee_Order", "[Operation_Date] = #" & Operation_Date & "# AND [Employee_ID]= " & Employee_ID & " AND [Order_ID] = " & Order_ID & " AND [Model_Operation_ID] = " & MO_ID)
Returns the expected values such as:
08/05/2015 2 526 1107 0
Apart from the last one, which is expected to be 1 (record already exists).
tbl2EmployeeOrder has this record:
Operation_Date: 08/05/2015
Employee_ID: 2
Order_ID: 526
Model_Operation_ID = 1107
Interestingly enough, it used to work without problem a few weeks ago, suddenly it behaves as if the record doesn't already exist.
Edit:
The following:
Debug.Print TypeName(Operation_Date), TypeName(Employee_ID), TypeName(Order_ID), TypeName(MO_ID)
Results in:
Date Integer Integer Integer
And those are also the variable types in the tbl2Employee_Order.
Similarly, if I use DLookup (with some column name) instead of DCount I get a Null value returned.

did you change regional settings ? how about
If DCount("*", "tbl2Employee_Order", _
"[Operation_Date] = #" & Format(Operation_Date,"mm/dd/yyyy") & _
"# AND [Employee_ID]= " & Employee_ID & _
" AND [Order_ID] = " & Order_ID & _
" AND [Model_Operation_ID] = " & MO_ID) = 0 Then
remove the date criteria to see if it works

Related

CheckIfExist. If exist don't insert the data, if not insert the data

I have a problem on how to insert data into two different table. So my requirements is this.
Under Group Details, The user need to click all the needed information on the dropdown menu and input on the textbox of the table grid view before clicking the ADD Link, after this the page will load displaying the Added Job Title and business group details. The user is allowed to input as many Job title as the user want.
I already finished the table but I have problems in saving the data that I input.
So my first table looks like this Before
and I edit it and this is my table Now
So my problem is this, in my database i have two table. One is EMPGROUP_TBL with columns SEQID, masterID, Business Unit, Division, Sub-Division etc. and the other is EMP_MASTERTBL with columns MasterID, Name, LastName, Jobtitle.
Now everytime I click Add link the jobtitle will not be able to save in the EMP_MASTERTBL so I create a code in VB.Net that will update the EMP_MASTERTBL table when I click the add button under Group Details.
Here's my codes.
If UpdateInsDelRecord("INSERT INTO EMPGROUP_TBL (MASTERID, BUSINESS_UNIT, " & _
"DIVISION, SUB_DIVISION, CLASSIFICATION, SUB_CLASSIFICATION) VALUES " & _
"('" & HandleQuote(Me.lblval_Empid.Text) & "', " & _
"'" & Me.ddl_BusinessUnit.SelectedValue.ToString() & "' ," & _
"'" & val_division & "' ," & _
"'" & val_subdivision & "' ," & _
"'" & Me.ddl_Classification.SelectedValue.ToString() & "' ," & _
"'" & Me.ddl_SubClassification.SelectedValue.ToString() & "')" & _
";" & _
"UPDATE EMP_MASTERTBL SET JOBTITLE = '" & Me.txtJobtitle.Text & "' " & _
"WHERE MASTERID = '" & Me.lblval_Empid.Text & "'") = True Then
Return True
Response.Redirect("eHR_EmpMaintenance.aspx")
Else
Return False
End If
But the user must be able to add as many as Jobtitle and EMPGROUP_TBL details as the user want. So I'm thinking that I'll just write another query for that? How can I add the Group Details and be able to add as many as Jobtitle as the user want?
CheckIfExist
I figured maybe I could use the CheckIfExist and if the employee has an existing data to the jobtitle, business unit, division, sub-division, classification and sub-classification similar to the one that you will add, the messagebox will show that the data already exist. If no data found then it will be able to add the details under the employee's group details. And if you input similar jobtitle but different business unit etc. the data will just be updated and vice versa.
Here's what my code for this.
Function SaveUserGroup() As Boolean
Try
Dim jobtitle As String = Me.txtJobtitle.Text
Dim businessunit As String = Me.ddl_BusinessUnit.SelectedValue
Dim division As String = Me.ddl_Division.SelectedValue
Dim subdivision As String = Me.ddl_SubDivision.SelectedValue
Dim classification As String = Me.ddl_Classification.SelectedValue
Dim subclassification As String = Me.ddl_SubClassification.SelectedValue
Dim CheckMasterTblIfExist As Boolean
Dim CheckGroupTblIfExist As Boolean
Dim insrtResult As Boolean
Dim seqid As String = Me.lblSEQID.Text
Dim emp_id As String = Request.QueryString("emp_id")
If jobtitle <> "" And businessunit <> "Please Select" And division <> "Please Select" And subdivision <> "Please Select" And classification <> "Please Select" And subclassification <> "Please Select" Then
CheckMasterTblIfExist = CheckRecord("SELECT MASTERID, JOBTITLE FROM EMP_MASTERTBL WHERE JOBTITLE = '" & jobtitle & "' AND MASTERID = '" & emp_id & "' ")
CheckGroupTblIfExist = CheckRecord("SELECT * FROM EMPGROUP_TBL WHERE BUSINESS_UNIT = '" & businessunit & "' AND DIVISION = '" & division & "' AND SUB_DIVISION = '" & subdivision & "' AND CLASSIFICATION = '" & classification & "' AND SUB_CLASSIFICATION = '" & subclassification & "' AND MASTERID = '" & emp_id & "' AND SEQID = '" & seqid & "'")
If Not CheckMasterTblIfExist And CheckGroupTblIfExist Then
insrtResult = UpdateInsDelRecord("UPDATE EMP_MASTERTBL SET JOBTITLE = '" & jobtitle & "' " & _
"WHERE MASTERID = '" + Me.lblval_Empid.Text + "'" & _
";" & _
"INSERT INTO EMPGROUP_TBL(MASTERID, BUSINESS_UNIT, " & _
"DIVISION, SUB_DIVISION, CLASSIFICATION, SUB_CLASSIFICATION) VALUES " & _
"('" & HandleQuote(Me.lblval_Empid.Text) & "', " & _
"'" & businessunit & "' ," & _
"'" & division & "' ," & _
"'" & subdivision & "' ," & _
"'" & classification & "' ," & _
"'" & subclassification & "')")
If Not insrtResult Then
MessageBox("alert('Error Ocurred While Inserting a Data.')")
Else
MessageBox("alert('Successfully Added.')")
End If
Else
MessageBox("alert('Data Already Exist.')")
End If
End If
Catch ex As Exception
MessageBox("Error Ocurred while Inserting a data")
Throw
End Try
End Function
I haven't been completed the code yet. I'm in the adding if there's no data and my problem is that the messagebox keeps on telling me that the data already exist even if there's still no employee's group details that added. Please help me with this.
begin tran
if exists (select * from table with (updlock,serializable) where key = #key)
begin
update table set ...
where key = #key
end
else
begin
insert into table (key, ...)
values (#key, ...)
end
commit tran
you can use like this

Can't find what is wrong with the code

I Have this code, and I can't figure out what is wrong with it. It does not return any error but field Date_Returned is not getting updated. Please help.
Private Sub txtbxret_Click()
Dim query As String
query = "UPDATE Rent SET Date_Returned = '" & Date & "' WHERE Date_Rent = " & txtrented.Value & " AND Customer_ID = " & txtbxcustID.Value & " AND Movie_ID = " & txtbxmovID.Value
DoCmd.RunSQL (query)
End Sub
I've double and triple checked all the field names and thay are ok by the way...
You must use proper formatting of string expressions of date values in SQL:
query = "UPDATE Rent SET Date_Returned = Date() WHERE Date_Rent = #" & Format(txtrented.Value, "yyyy\/mm\/dd") & "# AND Customer_ID = " & txtbxcustID.Value & " AND Movie_ID = " & txtbxmovID.Value

Access VBA: SQL query causes UPDATE syntax error

I have a database with linked tables- Staff, Courses and Training_Record. Each staff member has a numeric primary key, as does each course and each entry in the Training_Record table. The Staff_ID and Course_ID in the Training_Record reference records in Staff and Courses.
When a staff member or course is added, the Training_Record (fields: Staff_ID, Course_ID, Date_Taken, Notes) has staff,course records inserted- so adding staff member 1 would insert records (1,1,,,), (1,2,,,) etc, adding course 8 would insert records (1,8,,,), (2,8,,,) and so on. This works.
I then have a form to record training. The user selects the course, enters the date and selects staff members from a listbox. I have a save button which triggers VBA code. The date and course are pulled from the boxes and I loop round the listbox, concatenating selected staff members into a string. This all works and a message box displays, verifying that. Then, an update SQL query should be run, updating the Training_Record.
The problem I have is with the SQL update. I have an update query that will work in the SQL query editor, though it uses written in variables:
UPDATE Training_Record
SET Date_Taken = '12/12/12'
WHERE Staff_ID IN (1,2,3,4,5) AND Course_ID = 4
This updates the Training_Record to show that staff 1,2,3,4 and 5 took course 4 on 12/12/12. However, in VBA this will not work. This is my SQL query in VBA:
strSQL = "UPDATE Training_Record" _
& "SET Date_Taken = (" & strDate & ")" _
& "WHERE Staff_ID IN (" & strCriteria & ") AND Course_ID = (" & strCourse & ")"
DoCmd.RunSQL strSQL
The error that the code generates is "Run-time error '3144': Syntax error in UPDATE statement." and the debugger highlights the DoCmd.RunSQL statement following the query.The entire VBA code:
Private Sub SaveTraining_Click()
Dim db As DAO.Database
Dim VarItem As Variant
Dim strCriteria As String
Dim strDate As Variant
Dim strCourse As Variant
Dim strSQL As String
Set db = CurrentDb()
'Extract the course ID and the training date from the form
strCourse = Me!CourseID.Value
strDate = Me!TrainingDate.Value
'Dealing with empty boxes- zero length
If IsNull(strCourse) Then
MsgBox "Please select a course." _
, vbOKOnly, "No course selected"
End If
If IsNull(strDate) Then
MsgBox "Please enter a date." _
, vbOKOnly, "No date given"
End If
If StaffMembers.ItemsSelected.Count = 0 Then
MsgBox "Please select staff members." _
, vbOKOnly, "No staff members"
End If
If (Not IsNull(strCourse)) And (Not IsNull(strDate)) And (StaffMembers.ItemsSelected.Count > 0) Then
'Extract each selected member and concatenate into a string for sql query
For Each VarItem In Me!StaffMembers.ItemsSelected
strCriteria = strCriteria & "," & Me!StaffMembers.ItemData(VarItem)
Next VarItem
'Gets rid of extra comma on query string
strCriteria = Right(strCriteria, Len(strCriteria) - 1)
'Message box
MsgBox ("Staff: " & strCriteria & vbNewLine & "Date: " & strDate & vbNewLine & "Course: " & strCourse & vbNewLine & "No. Selected staff: " & StaffMembers.ItemsSelected.Count)
strSQL = "UPDATE Training_Record" _
& "SET Date_Taken = (" & strDate & ")" _
& "WHERE Staff_ID IN (" & strCriteria & ") AND Course_ID = (" & strCourse & ")"
DoCmd.RunSQL strSQL
End If
Set db = Nothing
End Sub
TL;DR I can't make a SQL UPDATE query run in VBA
I've got a feeling that it's an error in syntax somewhere, but I can't find where. Any ideas/advice would be much appreciated, thanks.
I think you are simply missing spaces at the end of the lines
You old query print out
UPDATE Training_RecordSET Date_Taken = ()WHERE Staff_ID IN () AND Course_ID = ()
as you can see there will be a name collision before keywords SET and WHERE
therefore change your strSQL to
strSQL = "UPDATE Training_Record " _
& "SET Date_Taken = (" & strDate & ") " _
& "WHERE Staff_ID IN (" & strCriteria & ") AND Course_ID = (" & strCourse & ")"
which prints out as (with no values provided)
UPDATE Training_Record SET Date_Taken = () WHERE Staff_ID IN () AND Course_ID = ()
which in terms of SQL syntax is correct
If I were you I would also check the data types of columns in your Training_Record table
Usually (and this applies to Type-mismatch error),
for dates you wrap the variable or value on both sides with #
example & "SET Date_Taken = (#" & strDate & "#) ...
for strings you use single quotes '
example WHERE Operator_Name = ('" & operName & "') ...
for numerical values you do not need to use anything but casting to provide the correct data type
My guess:
strSQL = "UPDATE Training_Record" _
& "SET Date_Taken = (#" & Format(strDate, "mm\/dd\/yyyy") & "#)" _
& "WHERE Staff_ID IN (" & strCriteria & ") AND Course_ID = (" & strCourse & ")"
If staff_ID is a string:
strSQL = "UPDATE Training_Record" _
& "SET Date_Taken = (#" & Format(strDate, "mm\/dd\/yyyy") & "#)" _
& "WHERE Staff_ID IN ('" & strCriteria & "') AND Course_ID = (" & strCourse & ")"

VBA Access - Multiple Tables count by date

We'd like to count from an Access database that has multiple tables - about 50.
We need to count from 1 column in each table that is 'QCPASS' This is a check box - if a product passed the box was checked if failed then not. We need to count both for EACH table, also allowing the user to specify a date range from a date column that exists in every table.
I've tried this with a query but I am told the query is unable to select, count and do the date range. Any VBA help would be great.
Exporting to Excel would be great, but any results would be fine. Here is the query I created that counts in a column from each table passes and failures. I can't iterate with a query either, so VBA seems the way to go:
SELECT "Table1" , Count('qcpass') AS column
FROM 5000028
GROUP BY [5000028].qcpass
union
SELECT "Table2",count('qcpass')
FROM 5000029
Group By [5000029].qcpass;
You can traverse the full TableDefs collection in your database, and create a query using VBA.
A word of warning: The TableDefs collection has the Access database system tables, so you need to skip this. A way I suggest you is to check for a specific table name prefix (it is noted in the code below).
public sub createMyBigUnionQuery()
dim db as DAO.database(), tbl as DAO.tableDef
dim strSQL as string, i as integer
set db = currentdb()
i = 1
for each tbl in db.TableDefs
if left(tbl.name, 1) = "5" then ' Check for a table name prefix
if i = 1 then
' The final spaces are important
strSQL = "select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"group by qcpass "
else
' The final spaces are important
strSQL = strSQL & " union all " & _
"select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"group by qcpass "
end if
i = i + 1
end if
next tbl
db.createQueryDef "qryYourFinalQuery", strSQL
db.close
exit sub
Notice that you can define any valid query you want. Take this as a hint, and tweak it to fit your specific needs.
Hope this helps you
Adressing #HansUp comment, if you need to filter your data by date, you have two options:
Include the where condition on every select created by the procedure
Include the date field in your query and group by it, and create a second query to filter the data you need from the created query.
I would personally go with option 1, and here is a sample code:
public sub createMyBigUnionQueryWithDates(d0 as date, d1 as date)
dim db as DAO.database(), tbl as DAO.tableDef
dim strSQL as string, i as integer
set db = currentdb()
i = 1
for each tbl in db.TableDefs
if left(tbl.name, 1) = "5" then ' Check for a table name prefix
if i = 1 then
' The final spaces are important
strSQL = "select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"where rowDate between " & cDbl(d0) & " and " &cDbl(d1) & " " & _
"group by qcpass "
else
' The final spaces are important
strSQL = strSQL & " union all " & _
"select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"where rowDate between " & cDbl(d0) & " and " &cDbl(d1) & " " & _
"group by qcpass "
end if
i = i + 1
end if
next tbl
db.createQueryDef "qryYourOtherFinalQuery", strSQL
db.close
exit sub
The reason I use cDbl(d0) is because Access dates are sensitive to regional settings, and I've had a lot of headaches dealing with it. Access (and many other Microsoft products) store dates as floating-point numbers (the integer part is the date, and the decimal part is the time).
Another word of warning: If your dates don't include time, then the between condition will work. But if they do include time, then I recommend you change the where condition to this:
"where rowDate >= " & cDbl(d0) & " and rowDate < " & cDbl(d1 + 1)"

How do I resolve this query?

I receive runtime error 3122 :
You tried to execute a query that does not include the specified expression count(*)*t2.Daily_Charge_HKD as part of the aggregate function
What I want to do in the query:
I want to group all the record in Opt_In_Customer_Record by event_plan_code, and have a total count for each of the code, then I reference the daily_charge from the daily_charge table by t1.event_plan_code = t2.event_plan_code, and multiply the daily_charge with the total count for each of the code
Here is my code:
Private Sub btnGenDaily_Click()
Dim filename As String
Dim prefix As String
Dim qryDef As DAO.QueryDef
Dim dbs As DAO.Database
Set dbs = OpenDatabase(CurrentDb.Name)
If IsNull(txtInputPath.value) Then
MsgBox "Please enter a valid input file location."
Else
If FileExists(txtInputPath.value) Then
If IsNull(txtOutputPath3.value) Then
MsgBox "Please enter a valid output file location."
Else
prefix = GetFileNamePrefix(txtInputPath.value)
sql = "select t1.event_plan_code, count(*), count(*)*t2.Daily_Charge_HKD " & _
"from Opt_In_Customer_Record t1 Inner Join Daily_Charge t2 " & _
"On (t1.event_plan_code=t2.event_plan_code and t2.Home_BMO='" & prefix & "') " & _
"group by t1.event_plan_code " & _
"order by t1.event_plan_code "
MsgBox sql
If ObjectExists("Query", "getDailyCharge") Then
DoCmd.DeleteObject acQuery, "getDailyCharge"
End If
With dbs
.QueryTimeout = 0
Set QueryDef = .CreateQueryDef("getDailyCharge", sql)
End With
strPathToSave = txtOutputPath3.value
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "getDailyCharge", strPathToSave, True
MsgBox "Daily charge report generated."
End If
Else
MsgBox "Input file does not exist. Please enter again."
End If
End If
End Sub
I know you mentioned in a comment that you don't want to group by "t2.Daily_Charge_HK", but to use that in the way you are doing with access you will need to group it, because of your join I'm guessing you only have one Daily Charge value for each event plan code so the grouping in this case won't be a problem. e.g. all event plan codes with id of 1 and Home BMO a prefix of x will have the same charge rate.
Change:
sql = "select t1.event_plan_code, count(*), count(*)*t2.Daily_Charge_HKD " & _
"from Opt_In_Customer_Record t1 Inner Join Daily_Charge t2 " & _
"On (t1.event_plan_code=t2.event_plan_code and t2.Home_BMO='" & prefix & "') " & _
"group by t1.event_plan_code " & _
"order by t1.event_plan_code "
Into:
sql = "select t1.event_plan_code, count(*), count(*)*t2.Daily_Charge_HKD " & _
"from Opt_In_Customer_Record t1 Inner Join Daily_Charge t2 " & _
"On (t1.event_plan_code=t2.event_plan_code and t2.Home_BMO='" & prefix & "') " & _
"group by t1.event_plan_code, t2.Daily_Charge_HKD " & _
"order by t1.event_plan_code, t2.Daily_Charge_HKD "
Hope this helps
Finally I come up with this solution and it works:
sql = "select t1.event_plan_code, Count, Count*Daily_Charge_HKD As 'Count * Daily_Charge_HKD' " & _
"from (select event_plan_code, count(*) As Count " & _
"from Opt_In_Customer_Record " & _
"group by event_plan_code " & _
"order by event_plan_code) t1, Daily_Charge t2 " & _
"where t1.event_plan_code=t2.event_plan_code and t2.Home_BMO='" & prefix & "' " & _
"order by t1.event_plan_code"