Two Date Criteria in DMin Function in VBA Access - vba

I have a table with Multiple Date Fields like
DOB (Date),
DOA_ASST(Date),
DOA_UDC (Date)
and also have some fields like
ID (AutoNumber),
EmpID (Integer),
EmpName (Text),
SeniorityNumber (Integer) etc.
Many of Employee Promoted Same Date and Also Have the same date of Appointment. I want to provide serial no as per their seniority according to their first date of Appointment.
Criteria are following-
if Multiple Employee Promoted on the Same date then Date of Appointment with older date will be considered, if Date of Appointment are same then Date of Birth with Older date will be considered.
I tried the following code:-
Private Sub cmdProcess_Click()
Dim rst As Recordset
Dim rst1 As Recordset
Dim LastSN As Integer
Dim str, strAsst, strUDC, strLDC As String
Dim LDCDate, UDCDate, AsstDate, BirthDate As Date
AsstDate = Nz(DMax("[DOP_ASST]", "tblDraftSeniority"), DMin("[DOP_ASST]", "tblRawSeniority"))
UDCDate = DMin("[DOP_UDC]", "tblRawSeniority", "[DOP_ASST] = #" & AsstDate & "#")
LDCDate = DMin("[DOA_ESIC]", "tblRawSeniority", "[DOP_UDC] = #" & UDCDate & "# AND [DOP_ASST] = #" & AsstDate & "#")
BirthDate = DMin("[DOB]", "tblRawSeniority", "[DOA_ESIC] = #" & LDCDate & "#")
LastSN = DLookup("[ID]", "tblRawSeniority", "[DOB] = #" & BirthDate & "#")
Set rst = CurrentDb.OpenRecordset("tblRawSeniority")
Set rst1 = CurrentDb.OpenRecordset("tblDraftSeniority")
rst.MoveLast
rst.MoveFirst
Do While rst.EOF = False
If rst!ID = LastSN Then
With rst
Me.txtEmpName1 = rst!EmpName
Me.txtEmpCatg1 = rst!Category
Me.txtEmpDOB1 = rst!DOB
Me.txtEmpDOEntry1 = rst!DOA_ESIC
Me.txtEmpDONextPromo1 = rst!DOP_UDC
Me.txtEmpDOCurrentPromo1 = rst!DOP_ASST
Me.txtEmpStateRegion1 = rst!Region
Me.txtRemark1 = rst!Remark
Me.txtSN1 = rst!SrNoHQRS
End With
End If
rst.MoveNext
Loop
Set rst = Nothing
End Sub
But there is null value in LDCDate with Two date Criteria

Since rst1 is not used, and you are only looking up one ID, you could try something like:
Private Sub cmdProcess_Click()
Dim rst As DAO.Recordset
Dim LastSN As Long
Dim LDCDate As Date
Dim UDCDate As Date
Dim AsstDate As Date
Dim BirthDate As Date
AsstDate = Nz(DMax("[DOP_ASST]", "tblDraftSeniority"), DMin("[DOP_ASST]", "tblRawSeniority"))
UDCDate = Nz(DMin("[DOP_UDC]", "tblRawSeniority", "[DOP_ASST] = #" & Format(AsstDate, "yyyy\/mm\/dd") & "#"), DMax("[DOP_UDC]", "tblRawSeniority"))
LDCDate = Nz(DMin("[DOA_ESIC]", "tblRawSeniority", "[DOP_UDC] = #" & Format(UDCDate, "yyyy\/mm\/dd") & "# AND [DOP_ASST] = #" & Format(AsstDate, "yyyy\/mm\/dd") & "#"), DMax("[DOP_ESIC]", "tblRawSeniority"))
BirthDate = DMin("[DOB]", "tblRawSeniority", "[DOA_ESIC] = #" & Format(LDCDate, "yyyy\/mm\/dd") & "#")
LastSN = Nz(DLookup("[ID]", "tblRawSeniority", "[DOB] = #" & Format(BirthDate, "yyyy\/mm\/dd") & "#"), Date)
Set rst = CurrentDb.OpenRecordset("tblRawSeniority")
rst.FindFirst "ID = " & LastSN & ""
If Not rst.NoMatch Then
Me.txtEmpName1 = rst!EmpName
Me.txtEmpCatg1 = rst!Category
Me.txtEmpDOB1 = rst!DOB
Me.txtEmpDOEntry1 = rst!DOA_ESIC
Me.txtEmpDONextPromo1 = rst!DOP_UDC
Me.txtEmpDOCurrentPromo1 = rst!DOP_ASST
Me.txtEmpStateRegion1 = rst!Region
Me.txtRemark1 = rst!Remark
Me.txtSN1 = rst!SrNoHQRS
End If
rst.Close
Set rst = Nothing
End Sub

Since you are allowing null values for AsstDate, you are most likely using a null value (or 0) in the criteria for the LDCDate DMin lookup. If your table doesn't actually have nulls in the DOP_ASST field, then your LDCDate will be null because there is no result found.

Related

Date filter returns an invalid character error

I want to execute a query with a date filter in Access VBA.
My first issue was inconsistent datatypes: expected DATE got NUMBER.
I assume Access stores dates as numbers just like Excel.
I found I had to use "#" between the date for the query to recognize it as a DATE. Now I am getting an INVALID CHARACTER error which means the hash # is an invalid character.
I have to pull in the negotiated costs with our vendors that don't have more than 60 days of being expired.
There is also a tblVendors where the user selects the vendor ID (ORDID) they want to pull the info from. That's why I do a loop to pull in every ORDID in that table. I don't push in all the ORDID in one try because it brings a lot of data and doing it in batches runs faster.
Sub GetMaterialCost()
Dim db As Database
Dim rsData As ADODB.Recordset, rsVendor As DAO.Recordset, rsItemCost As DAO.Recordset
Dim strQuery As String
Dim vendorNO As Long, dtDate As Date
Set db = CurrentDb
dtDate = Format(Now() - 60, "m/d/yyyy")
Set rsVendor = db.OpenRecordset("SELECT ORDID, VEN_NAME, USER_ID FROM tblVendors WHERE ACTIVE = TRUE ORDER BY VEN_NAME, ORDID")
Set rsItemCost = db.OpenRecordset("tbl_ItemCost")
ConnectBILL
rsVendor.MoveFirst
Do Until rsVendor.EOF
strQuery = "SELECT MASID, LOCATION, ITEM, ITEM_QTY, ITEM_UOM, ITEM_COST, EXP_DT " _
& "FROM ITEMMASTER INNER JOIN ORDDETAIL ON (ITEMMASTER.ITEM = ORDDETAIL.ITEM) " _
& "WHERE (LOCATION IN (AS1,AS3,AS6) AND TRIM(MASID) = '" & Cstr(rsVendor.Fields("ORDID")) & "' AND EXP_DT >= #paramDate)"
With ComBill
.CommandText = strQuery
Set rsData = .Execute(, Array(dtDate))
end with
'clears previous instance of vendor data by vendor_no if it exists
db.Execute "DELETE * FROM tbl_ItemCost WHERE MASID LIKE '*" & rsVendor.Fields("ORDID") & "*'"
'starts inserting queried data
rsData.MoveFirst
Do Until rsData.EOF
With rsItemCost
.AddNew
.Fields("MASID") = rsData!MASID
.Fields("LOCATION") = rsData!LOCATION
.Fields("ITEM") = rsData!ITEM
.Fields("ITEM_UOM") = Trim(rsData!ITEM_UOM)
.Fields("ITEM_COST") = rsData!ITEM_COST
.Fields("EXP_DT") = rsData!EXP_DT
.Update
End With
rsData.MoveNext
Loop
rsVendor.MoveNext
Loop
End Sub
Correct these two lines:
dtDate = DateAdd("d", -60, Date)
& "WHERE LOCATION IN (AS1,AS3,AS6) AND TRIM(MASID) = '" & CStr(rsVendor.Fields("ORDID") & "' AND EXP_DT >= #" & Format(dtDate, "yyyy\/mm\/dd") & "#) "
Note, that for ADO, string expressions for date values must be formatted using the ISO sequence.
If the field EXP_DT is Text:
& "WHERE LOCATION IN (AS1,AS3,AS6) AND TRIM(MASID) = '" & CStr(rsVendor.Fields("ORDID") & "' AND EXP_DT >= '" & Format(dtDate, "m\/d\/yyyy") & "') "

VBA SQL string saving short date as General date instead of short

I'm trying to do something basic:
Take 2 dates [startD] and [endD] from a accdb file.
Move them forward one month each
save the new dates as short dates in the respective record.
I'm doing this all by VBA
The issue is that it is showing the correct SQL String (if i do msgbox sql) however when it saves, it is saving as a general date with time and is the wrong value!
*Note: I'm in Australia so I have a format section to make sure the date saves correctly.
I have tried using DateValue() and Formatting the date too.
Dim frq As Integer
Dim wks As Integer
Dim CurAcc As Integer
Dim CurAccEnd As Date
Dim Days As Integer
Dim curaccvalue As Currency
Dim cardtype As Integer
Dim cardcharged As Integer
cardtype = 0
cardcharged = 0
CurAcc = Me.ID
curraccvalue = DLookup("Acccurvalue", "Accounts", "[ID] = " & CurAcc)
Curraccend = DLookup("Accend", "Accounts", "[ID] = " & CurAcc)
frq = DLookup("freqid", "Accounts", "[ID] = " & CurAcc)
wks = DLookup("freqvalue", "tblfrequency", "FrequencyID = " & frq)
Days = wks * 7
strsql = "UPDATE Accounts SET AccStart = " & Date & " , AccEND = " &
Curraccend + Days & " , AccCurValue = 0.00 WHERE ID = " & CurAcc
MsgBox strsql
DoCmd.RunSQL strsql
When implicitly converting a date to a string, your regional settings are used, but in a SQL string, a date must be in the American format.
To avoid this, I suggest to do the update in just one query:
Dim strSql As String
strSql = "UPDATE Accounts " & _
"INNER JOIN tblfrequency ON Accounts.freqid = tblfrequency.FrequencyID SET " & _
"AccStart = Date(), " & _
"AccEND = DateAdd(""w"", tblfrequency.freqvalue, Accounts.Accend), " & _
"AccCurValue = 0.00 WHERE ID = " & Me.ID
MsgBox strSql
DoCmd.RunSQL strSql

Visual Basic 2010 DataGridView Filter is not working

Both code snippets don't work.
My column name is Shipment End in DataGridView1
Dim az As Date = DateTimePicker3.Value
Dim bz As Date = DateTimePicker4.Value
Me.Sheet1BindingSource.Filter = "([Shipment End]<= '" & DateTimePicker3.Value & "' and [Shipment End]>= '" & DateTimePicker4.Value & ")"
and
Dim DateFrom As String = String.Format("Shipment End >= '{0:yyyy-MM-dd}' ", DateTimePicker3.Value)
Dim DateTo As String = String.Format("Shipment End <= '{0:yyyy-MM-dd}' ", DateTimePicker4.Value)

How do you find if a record exists?

Dim mydb As DAO.Database
Dim myrst As DAO.Recordset
Dim Date1, Date2 As Date
Dim mysql As String
Dim qdf As QueryDef
Dim EmployeeID As String
EmployeeID = DLookup("lngEmpID", "tblEmployees", "Forms!frmEmployeeOrderForm.cboEmployeeName.Value = EmployeeName")
Me.EmpID = EmployeeID
PickupTime = DLookup("Pickup", "tblEmployees", "Forms!frmEmployeeOrderForm.cboEmployeeName.Value = EmployeeName")
Me.PickupDay = PickupTime
Set mydb = CurrentDb
Date1 = Me.dtmGiveAwayDate1
Date2 = Me.dtmGiveAwayDate2
mysql = ("Select tblOrders.lngEmpID, tblOrders.dtmGiveAwayDate1, tblOrders.dtmGiveAwayDate2 FROM tblOrders WHERE tblOrders.lngEmpID =" & EmployeeID & " AND tblOrders.dtmGiveAwayDate1 =" & Date1 & " AND tblOrders.dtmGiveAwayDate2 =" & Date2)
MsgBox mysql
Set myrst = mydb.OpenRecordset(mysql)
If myrst.EOF = False Then
MsgBox "You have already ordered for this PFG." & vbCrLf & "Please see Jody for help."
cmdCancel_Click
Exit Sub
End If
When I run the program I am trying to prevent employees from entering their name twice for the same dates. To test I tried to duplicate a record for the same employee and it will not trigger the myrst.eof = false and display the message box that says "You have already ordered for this PFG". Any help is much appreciated.
Thank you in advance.
Use the FindFirst method :
myrst.FindFirst "field = " & value
If myrst.NoMatch Then
//code when record doesn't exist
End If
Checking for equality with dates can be tricky. Since VBA dates can include time to the nanosecond, could it be that one side (SQL/code) has a real time, while the other has the default midnight value?
Set mydb = CurrentDb
Date1 = Format(Me.dtmGiveAwayDate1, "Short Date")
Date2 = Format(Me.dtmGiveAwayDate2, "Short Date")
mysql = ("Select tblOrders.lngEmpID, tblOrders.dtmGiveAwayDate1, tblOrders.dtmGiveAwayDate2 FROM tblOrders WHERE tblOrders.lngEmpID =" & EmployeeID & " AND tblOrders.dtmGiveAwayDate1 =" & "#" & Date1 & "#" & " AND tblOrders.dtmGiveAwayDate2 =" & "#" & Date2 & "#")
MsgBox mysql
Set myrst = mydb.OpenRecordset(mysql)
This was the code I used and it works now. Thank you.

sending multiple parameters from form to report query

Trying to send three variables (startDate, endDate, division) from a chooser form to a report query. Sent the three variables through an doCommand.OpenReport command, then unpacked them in the Load event of the report. I'm not sure what to assign them to in the report to use them in the query.
In the form:
Private Sub btn_bud_sum_exp_div_Click()
Dim StrWhereCondition
Dim a As String
Dim b As String
Dim c As String
a = Me.txtStartDate.Value
b = Me.txtEndDate.Value
c = Me.lstDivision.Value
StrWhereCondition = a & "|" & b & "|" & c
'StrWhereCondition = "[accounting start date] = " & Me.txtStartDate.Text
DoCmd.OpenReport "FY15 Budget Line Sum - Expenditures - Div", , , StrWhereCondition
End Sub
In the Load event of the report:
Private Sub Report_Load()
Dim dtStartDate As Date
Dim dtEndDate As Date
Dim strDivision As String
If Not IsNull(Me.OpenArgs) Then
dtStartDate = parsetext(OpenArgs, 0)
dtEndDate = parsetext(OpenArgs, 1)
strDivision = parsetext(OpenArgs, 2)
End If
End Sub
In the report query:
SELECT
*
FROM
budget b
WHERE
(b.start_date between dtStartDate AND dtEndDate) AND d.division = strDivision
If you open the report with a filter string, you can delete all the OnLoad stuff of the report:
Private Sub btn_bud_sum_exp_div_Click()
Dim StartDate As String
Dim EndDate As String
Dim Division As String
Dim WhereCondition As String
StartDate = Format(Me!txtStartDate.Value, "yyyy\/mm\/dd")
EndDate = Format(Me!txtEndDate.Value, "yyyy\/mm\/dd")
Division = Me!lstDivision.Value
WhereCondition = "start_date between #" & StartDate & "# and #" & EndDate & "# and division = " & Division & ""
' or:
' WhereCondition = "[accounting start date] between #" & StartDate & "# and #" & EndDate & "# and division = " & Division & ""
' or, if division is text:
' WhereCondition = "start_date between #" & StartDate & "# and #" & EndDate & "# and division = '" & Division & "'"
DoCmd.OpenReport "FY15 Budget Line Sum - Expenditures - Div", , , WhereCondition
End Sub