如何将SQL查询的结果保存到VBA中的变量中?

时间:2014-06-02 10:18:40

标签: sql vba ms-access

我想执行一个select语句并将它的结果(只有1个记录,带有1个值)放在一个变量中。

这是访问中的VBA代码。

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

2 个答案:

答案 0 :(得分:18)

只需让您的函数返回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

答案 1 :(得分:0)

通过使用“DLookup”函数,您几乎可以在一行中完成此操作

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

其中 Child 是您要查找的记录的 ID。