web-dev-qa-db-ja.com

SQLクエリの結果をVBAの変数に保存する方法は?

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
11
k0enf0rNL

関数に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
20
Gord Thompson