简体   繁体   中英

Access - Get latest date if column contains value from another one

I'm having an issue with a VBA function for my query in Access.
I have a table " tbldata "

Equipment   Last Inspection
420-413     2019-06-15
440-433     2019-06-15
402-483     2019-06-29
420-413     2019-12-12

and a query " qryunpair "

UnpairEquipment
420 
413 
440 
433 
402 
483 

What I'm trying to achieve is:

Equipment Latest Date
420       2019-12-12
413       2019-12-12
440       2019-06-15
433       2019-06-15
402       2019-06-29
483       2019-06-29

I've made the following code, but when I ran it, it didn't return any values. Is there a solution to this?

Function typeinspection(Source As String) As String
Dim Rst As Recordset
Dim Rst2 As Recordset
Dim s As String
    s = ""
    Set Rst = CurrentDb.OpenRecordset("tbldata")
    Set Rst2 = CurrentDb.OpenRecordset("qryunpair")
    While Not Rst.EOF

        If InStr(Source, Rst2.Fields("UnpairEquipment") > 0) Then _
            s = Rst.Fields("Last Inspection")
        Rst.MoveNext
    Wend

    Set Rst = Nothing
    Set Rst2 = Nothing
    typeinspection = s

End Function

If you want a query that returns your expected results, you can join the table and the query with the use of the operator LIKE :

SELECT q.UnpairEquipment AS Equipment, MAX([Last Inspection]) AS [Latest Date]
FROM qryunpair AS q INNER JOIN tbldata AS t
ON '-' + t.Equipment + '-' LIKE '*-' +  q.UnpairEquipment + '-*'
GROUP BY q.UnpairEquipment

Results:

Equipment   Latest Date
402         2019-06-29
413         2019-12-12
420         2019-12-12
433         2019-06-15
440         2019-06-15
483         2019-06-29

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM