How to save the result of a SQL query into a variable in VBA? How to save the result of a SQL query into a variable in VBA? vba vba

How to save the result of a SQL query into a variable in VBA?


Simply have your Function return the value from the Recordset:

Public Function rubrieknaamSQL(Child As Integer)   Dim rst As DAO.Recordset   Dim strSQL As String   strSQL = "SELECT rubrieknaam FROM dbo_tbl_rubriek where rubrieknummer = " & Child & ""   Set rst = CurrentDb.OpenRecordset(strSQL)   ' new code:   rubrieknaamSQL = rst!rubrieknaam   rst.Close   Set rst = NothingEnd Function


You can do this in pretty much one line by using the "DLookup" Function

rubrieknaam = Nz(DLookup("rubrieknaam ", "dbo_tbl_rubriek ", rubrieknummer & " =[Child]"), 0)

where Child is the ID of the record you are looking for.