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

时间:2022-11-19 22:06:34

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

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

This is in VBA code in access.

这是访问中的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

1 个解决方案

#1


16  

Simply have your Function return the value from the Recordset:

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


16  

Simply have your Function return the value from the Recordset:

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