Dlookup value shows 0 - ms-access

while using Dlookup to find a "part No" while using a textbox and entering Part no that will match to the last date entry and bring all information .
Dim prtn As String
Dim temppart As String
Dim lastdate As Date
temppart = Me.Part_No.Value
lastdate = Nz(DMax("[Date Of Purchase]", "StockInventory", "[Part No]= '" & temppart & "'"), 0)
prtn = Nz(DLookup("[Part No]", "[StockList Query]", "[Part No]='" & temppart & "' AND [Date Of Purchase]= " & Format(lastdate, "\#mm\/dd\/yyyy\#")), 0)
here i can see lastdate carry last date, temppart carry the part no but value in prtn shows 0 ..

ComputerVersteher: missing of data column which was cause to get value '0' issue resolved after adding the column to the current query.

Related

Using Null in a DLookup Criteria

I am creating a database to manage the flow of people in and out of an incident system. My idea is to use the DLookup function to allow me to identify a null value in the checkout date. This would allow me to prevent someone from jumping incidents without signing out first.
If it is possible I would like to get the EVENT ID and the COMMAND POST ID so I can create an error message to tell me the incident that is member is still attached to.
'***Section 1 - Ensure member is Checked out and DEMOBed from previous incidents
'******Variables
'*********Variable to hold the Member ID
Dim id As Integer
'*********Variable to hold the checkout status
Dim checkout As String
'*********Variable to hold the Event ID
Dim eventID As Integer
'******Code Block 1 - Check for Null Values
id = Me.Text18
Forms![frm_ics238Table].Refresh
If Not IsNull(DLookup("[eventID]", "[frm_ics238Table]", "[checkoutDate] is Null And employeeID = '" & Me.Text18 & "'")) Then
MsgBox "y"
End If
End Sub
From your original question which right now it doesn't look like you've edited it to indicate the updated code and errors, you had:
id = Me.Text18
Forms![frm_ics238Table].Refresh
If Not IsNull(DLookup("[eventID]", "[frm_ics238Table]", "[checkoutDate] is Null And employeeID = '" & Me.Text18 & "'")) Then
MsgBox "y"
End If
I think these might help:
"[frm_ics238Table]" should be table:"[tbl_ics238Table]"
ID appears to be declared as an integer yet you're using it as a
string. If employeeID is actually a numeric field remove the quotes
around employeeID = '" & Me.Text18 & "'" It should look like this employeeID = " & ID & "
You can also try using IsNull([checkoutDate]) instead of
[checkoutDate] is Null
SO it might look like:
If Not IsNull(DLookup("[eventID]", "[tbl_ics238Table]", "IsNull([checkoutDate]) And (employeeID = " & ID & ")")) Then
MsgBox "y"
End If
Even better would be to put the criteria into a string variable so you could debug and test it first
Dim strCriteria as String
strCriteria = "IsNull([checkoutDate]) And (employeeID = " & ID & ")"
Debug.Print strCriteria
If Not IsNull(DLookup("[eventID]", "[tbl_ics238Table]", strCriteria)) Then
MsgBox "y"
End If
EDIT: PROOF OF WORKING CODE:
Not that I don't believe you but I don't believe that it doesn't work if what you've described matches my assumptions.
I tested successfully using assumptions that:
eventID - number field
checkoutDate - date/time field
employeeID - number field
My sample data table
Then I put a command button on a form to test the code:
Private Sub Command8_Click()
Dim strCriteria As String
Dim ID As Integer
ID = 4
strCriteria = "IsNull([checkoutDate]) And (employeeID = " & ID & ")"
Debug.Print strCriteria
If Not IsNull(DLookup("[eventID]", "[tbl_ics238Table]", strCriteria)) Then
MsgBox "y"
End If
End Sub
Finally - testing the button click resulted in:
In conclusion - if you're still getting an error then you can update
your question with BOTH your code AND your table design.

MSAccess VBA, filtering query results via combo box (text)

I want to filter date values (text) in a query based on a comboBox text value.
Here is what I have:
ComboBoxTimePeriod (ID [num], TimePeriod [text]).
In ComboBox I select Time period, like "16.10.2017-15.11.2017".
In a query I have Date field with single date, like "20.10.2017" (text).
What I want is to write an SQL code which searches for all records with date within TimePeriod range.
So far Idea is to extract SatrtDate and EndDate from TimePeriod like this:
Dim strStartDate As String
Dim strEndDate As String
strStartDate = Mid(Me.cboTimePeriod.Text, 1, 10)
strEndDate = Mid(Me.cboTimePeriod.Text, 12, 10)
Now from TimePeriod "16.10.2017-15.11.2017" I have StartDate (16.10.2017) and EndDate (15.11.2017).
And I want to filter all records which have date within those two dates.
This is where I need you guys.
Note that this is different issue from my last question, where I searched for a records with TimePeriodID (Subform filtering based off multiple parameters (Combobox AND Textbox)).
Always handle dates as Date, not text:
Dim StartDate As Date
Dim EndDate As Date
StartDate = DateValue(Split(Me.cboTimePeriod.Value, "-")(0))
EndDate = DateValue(Split(Me.cboTimePeriod.Value, "-")(1))
The build your filter:
... " Between #" & Format(StartDate, "yyyy\/mm\/dd") & "# And #" & Format(EbdDate, "yyyy\/mm\/dd") & "#"
To filter a form:
Me.Filter = "[Date Field] Between #" & Format(StartDate, "yyyy\/mm\/dd") & "# And #" & Format(EbdDate, "yyyy\/mm\/dd") & "#"
Me.FilterOn = True
And do make sure that your Date Field is of data type Date, not Text.

Getting date from a query which is not showing exact as entered in table

I want to get MAX purchase date from a query.
I have written code which can show date in message box. But problem is that the date is not showing exactly as entered in the table. In the table date is 11-04-17, but in the message box date is shown 30-12-99.
My Code is:
Dim dbforPurdate As Database
Dim rsforPurdate As Recordset
Dim vmedid As String
Dim dtpurtbl As Date
Dim Qryfordate As String
vmedid = Me.MedID
Set dbforPurdate = CurrentDb
'Qryfordate = "SELECT Purchaset.[Purchase Date] AS PurDate, PurchaseDetailt.[Receipt No], PurchaseDetailt.MedID, PurchaseDetailt.BatchNo FROM Purchaset INNER JOIN PurchaseDetailt ON Purchaset.[Receipt No] = PurchaseDetailt.[Receipt No]"
Set rsforPurdate = dbforPurdate.OpenRecordset("Qryfordate")
dtpurtbl = Nz(DMax("[Purchase Date]", "qryfordate", [MedID] = "'" & vmedid & "'"), 0)
MsgBox Format(dtpurtbl, " dd/mm/yy ")
Your DMax() is not finding a value which returns Null and therefore the Nz() returns 0 and the Format() function converts 0 to 30-12-99.
The DMax() shows syntax errors and I am surprised you do not get runtime error. It is missing quote mark in front of [MedID] and has an extra quote mark after = sign.
Is MedID really a text type field?
DMax("[Purchase Date]", "qryfordate", "[MedID] = '" & vmedid & "'")
If you want the message box to not show the funky date value:
MsgBox IIf(dtpurtbl = 0, "No Date", Format(dtpurtbl, " dd/mm/yy "))

How to filter a form with multi-Field in MS Access using VBA

I have the code below in a click button event in MS Access 2013 form, whose datasource is from a query with the following fields “EnrNo, FirstName, LastName, and RegDate”.
The form has three text boxes and a command button:
txtKeyword
txtDateFrom
txtDateTo
cmdSearch
The click button (cmdSearch) in the form is intended to filter the query based on three criteria’s , which could be any of the two “EnrNo, FirstName, LastName” AND the range of the date(s) entered in the text box txtDateTo and cmdSearch
My code successfully filters only EnrNo. Please help me out... Thanks for your time.
Private Sub cmdSearch_Click()
Dim strWhere As String 'The criteria string.
Dim Where As String
Dim lngLen As Long 'Length of the criteria string to append to.
Const conJetDate = "\#mm\/dd\/yyyy\#" 'The format expected for dates in a JET query string.
'Text field example. Use quotes around the value in the string.
If Not IsNull(Me.txtFilter) Then
strWhere = strWhere & "([EnrNo] = """ & Me.txtFilter & """) OR "
strWhere = strWhere & "([FirstName] = """ & Me.txtFilter & """) AND "
End If
'Date field example. Use the format string to add the # delimiters and get the right international format.
If Not IsNull(Me.txtFrom) Then
strWhere = strWhere & "([RegDate] >= " & Format(Me.txtFrom, conJetDate) & ") AND "
End If
'Another date field example. Use "less than the next day" since this field has times as well as dates.
If Not IsNull(Me.txtTo) Then 'Less than the next day.
strWhere = strWhere & "[RegDate] BETWEEN #" & Format(Me.txtFrom, "mm/dd/yyyy") & "# AND #" & Format(Me.txtTo, "mm/dd/yyyy") & "# "
End If
lngLen = Len(strWhere) - 5
If lngLen <= 0 Then 'Nah: there was nothing in the string.
MsgBox "No criteria", vbInformation, "Nothing to do."
Else 'Yep: there is something there, so remove the " AND " at the end.
strWhere = Left$(strWhere, lngLen)
'Debug.Print strWhere
Me.Filter = strWhere
Me.FilterOn = True
End If
End Sub
It displays “Run-time error ‘3075’: Syntax error in data in query expression ‘([EnrNo] = “MS-12/IT-004”) or ([FirstName] = “MS-12/IT-004”) AND ([RegDate] >= #06/16/2014#) AND [RegDate] BETWEEN #06/16/2014# AND #09/23/2’ you have too many operands here.
You will need to make it so your query's where statement is as follows;
(([EnrNo] = “MS-12/IT-004”) or ([FirstName] = “MS-12/IT-004”)) AND (([RegDate] >= #06/16/2014#) AND ([RegDate] BETWEEN #06/16/2014# AND #09/23/2014#))
Note the extra brackets I have placed in there. Logical operators (OR/AND) will return a value based upon TWO expressions. So for instance, a > b AND b > c returns true if BOTH conditions are true. a > b OR b > c returns true if EITHER statement is true.
If we write a statement like a > b and b > c or d > f we have too many conditions, so we need to nest them. So we would write it as (a > b AND b > c) OR d > f.
A good way to practice this is to create the query with the criteria manually in the query builder, then look at the bracketing placed on your conditions in the SQL view window of the query.
I hope this helps!

Fill Field When All Checkboxes Toggled Access 2010

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 "