简体   繁体   中英

Access VBA -- unable to use a user-defined function

I wrote a function to use in an Access Query. The function work once but now it reverts back to the start of the routine when "Set rs = db.OpenRecordset etc." is hit.

Public Function RaceOutlook()

Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim Fav1 As Integer
Dim Fav2 As Integer
Dim Outlook As Integer
Dim Pace As Integer
Dim nFav1 As Field
Dim nFav2 As Field
Dim nOutlook As Field
Dim nPace As Field
Set db = CurrentDb 'tells program to use the current db
Set rs = db.OpenRecordset("Race Card Contenders", dbOpenDynaset)


Fav1 = rs("nFav1")
Fav2 = rs("nFav2")
Outlook = rs("nOutlook")
Pace = rs("nPace")


Select Case True
    Case (Fav1 = 1 And Fav2 = 3 And Outlook = 1 And Pace = 5)
    RaceOutlook = 1
    Case Else
    RaceOutlook = 0
End Select
rs.Close
End Function

In the MS Access UI (.exe only not ODBC/OLEDB) you can call a user-defined inline function directly from an SQL query even passing parameters with no need for opening the same recordset:

VBA function (to be placed in a module)

Public Function RaceOutlook(Fav1 As Integer, Fav2 As Integer, _
                            Outlook As Integer, Pace As Integer)

    Select Case True

       Case (Fav1 = 1 And Fav2 = 3 And Outlook = 1 And Pace = 5)
       RaceOutlook = 1

       Case Else
       RaceOutlook = 0

    End Select

End Function

SQL query

SELECT r.*, 
       RaceOutlook(r.fav1, r.fav2, r.Outlook, r.Pace) As RaceOutlook
FROM [Race Card Contenders] r

However, as commented, the VBA function does not offer more than Access's IIF() expression. Plus, below alternative query will work if connected to the database externally via ODBC/OLEDB:

SELECT r.*, 
       IIF(r.fav1=1 AND r.fav2=3 AND r.Outlook=1 AND r.Pace=5, 1, 0) As RaceOutlook
FROM [Race Card Contenders] r

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