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
1
  • Why can't you just store the value of the record with myVar = rst!nameOfValueField ? Commented Jun 2, 2014 at 10:32

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

5 Comments

was my first time making such a query in vba. thanks anyways!
what does the ! in rst!rubrieknaam do?
@Jorge - See the related question here.
This only returns the first matching result. How would you return ALL results that match the query?
@PatrickConwell - You process each row by looping through the recordset with Do Until rst.EOF and rst.MoveNext
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.