I would create a UDF and use the UDF in a query.
The UDF might be something like
Code:
Public Function fGetPrevDate(pItem As String, pDateOrdered As Date, Optional pVendor As String) As Date
Dim r As DAO.Recordset
Dim sSQL As String
'default return date
fGetPrevDate = #1/1/1900#
sSQL = "SELECT TOP 1 OrderDate"
sSQL = sSQL & " FROM PurchaseOrders"
'include Vendor name?
If Len(Trim(pVendor & "")) = 0 Then
sSQL = sSQL & " WHERE [ItemOrdered] = '" & pItem & "' and [OrderDate] < #" & pDateOrdered & "#"
Else
sSQL = sSQL & " WHERE [ItemOrdered] = '" & pItem & "' and [OrderDate] < #" & pDateOrdered & "# And [VendorName] = '" & pVendor & "'"
End If
sSQL = sSQL & " ORDERBY OrderDate DESC;"
' Debug.Print sSQL
CurrentDb.Execute sSQL, dbFailOnError
If Not r.BOF And Not r.EOF Then
fGetPrevDate = r("OrderDate")
End If
r.Close
Set r = Nothing
End Function
Place this in a standard module.
Usage in a query without the Vendor name would look like
Code:
PrevDate: fGetPrevDate(ItemOrdered, OrderDate)
Usage in a query with the Vendor name would look like
Code:
PrevDate: fGetPrevDate(ItemOrdered, OrderDate, [Vendor Name])
Note: you shouldn't use spaces in object names (especially field names)
If you wanted "Never Ordered" returned and not "1/1/1900", you could try
Code:
Public Function fGetPrevDate(pItem As String, pDateOrdered As Date, Optional pVendor As String)
Dim r As DAO.Recordset
Dim sSQL As String
'default return value
fGetPrevDate = "Never Ordered"
sSQL = "SELECT TOP 1 OrderDate"
sSQL = sSQL & " FROM PurchaseOrders"
'include Vendor name?
If Len(Trim(pVendor & "")) = 0 Then
sSQL = sSQL & " WHERE [ItemOrdered] = '" & pItem & "' and [OrderDate] < #" & pDateOrdered & "#"
Else
sSQL = sSQL & " WHERE [ItemOrdered] = '" & pItem & "' and [OrderDate] < #" & pDateOrdered & "# And [VendorName] = '" & pVendor & "'"
End If
sSQL = sSQL & " ORDERBY OrderDate DESC;"
' Debug.Print sSQL
CurrentDb.Execute sSQL, dbFailOnError
If Not r.BOF And Not r.EOF Then
fGetPrevDate = r("OrderDate")
End If
r.Close
Set r = Nothing
End Function
BTW.... this code is air code - untested!