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

2

20

I want to execute a select statement and put the result of it (which is only 1 record with 1 value) in a variable.

This is in VBA code in access.

Private Sub Child_Click()
   Dim Childnummer As Integer
   Dim childnaam As String
   Childnummer = Me.Keuzelijst21.Value
   DoCmd.Close
   DoCmd.OpenForm "submenurubrieken", acNormal, , " rubrieknummer = " & Childnummer & ""
   childnaam = rubrieknaamSQL(Childnummer)
   Forms!submenurubrieken.Tv_rubrieknaam.Value = childnaam
End Sub

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)
End Function
Scratches answered 2/6, 2014 at 10:18 Comment(1)
Why can't you just store the value of the record with myVar = rst!nameOfValueField ?Bernhardt
C
28

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 = Nothing
End Function
Counterproof answered 2/6, 2014 at 11:17 Comment(6)
was my first time making such a query in vba. thanks anyways!Scratches
what does the ! in rst!rubrieknaam do?Honey
@Honey - See the related question here.Counterproof
This only returns the first matching result. How would you return ALL results that match the query?Nonconductor
@PatrickConwell - You process each row by looping through the recordset with Do Until rst.EOF and rst.MoveNextCounterproof
Ah! Okay, thank youNonconductor
C
0

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.

Calistacalisthenics answered 4/5, 2021 at 22:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.