如何使用 VBA Access 将 SQL 查询结果传递给变量

How to pass a SQL query result to variable with VBA Access

我需要创建一个独立函数来检查值是真还是假。我试图设置一个执行此操作的 SQL 查询,但无法将结果传递给变量。

查询总是return只有一条记录。

如何将 SQL 字符串的结果作为函数的 returning 值传递?

已更新

Private Function HasBM(iMandate As Variant) As Boolean
'Returns boolean value for whether or not mandate has a benchmark
Dim sSQL1 As String
Dim sSQL2 As String

Dim db As Database
Dim rs As Recordset

sSQL1 = "SELECT tbl_Mandate_Type.BM_Included " & _
        "FROM tbl_Mandate_Type INNER JOIN tbl_MoPo_BM ON tbl_Mandate_Type.Mandate_Type_ID = tbl_MoPo_BM.MandateType_ID " & _
        "WHERE (((tbl_MoPo_BM.MoPo_BM_ID)="

sSQL2 = "));"

Set db = CurrentDb
Set rs = db.Execute(sSQL1 & iMandate & sSQL2)
HasBM = rs.Fields(0).Value

End Function

更新 2:解决方案

感谢 Magisch 和 HansUp 我最终得到了两个有效的解决方案:

Magisch 的 DLOOKUP 解决方案 我实现它时:

Private Function HasBM2(iMandate As Variant)
'Returns boolean value for whether or not mandate has a benchmark
Dim tmp As String

tmp = CStr(DLookup("tbl_MoPo_BM.MandateType_ID", "tbl_MoPo_BM", "tbl_MoPo_BM.MoPo_BM_ID = " & iMandate))
HasBM2 = DLookup("tbl_Mandate_Type.BM_Included", "tbl_Mandate_Type", "Mandate_Type_ID =" & tmp)

End Function

第二个解决方案使用记录集 作为 HansUp 帮助创建:

Private Function HasBM(iMandate As Variant) As Boolean
'Returns boolean value for whether or not mandate has a benchmark
Dim sSQL1 As String
Dim sSQL2 As String

Dim db As Database
Dim rs As dao.Recordset

sSQL1 = "SELECT tbl_Mandate_Type.BM_Included " & _
        "FROM tbl_Mandate_Type INNER JOIN tbl_MoPo_BM ON tbl_Mandate_Type.Mandate_Type_ID = tbl_MoPo_BM.MandateType_ID " & _
        "WHERE (((tbl_MoPo_BM.MoPo_BM_ID)="

sSQL2 = "));"

Set db = CurrentDb
Set rs = db.OpenRecordset(sSQL1 & iMandate & sSQL2)
HasBM = rs.Fields(0).Value

rs.close    

End Function

您可以使用本机的DLookup函数来访问它。由于您的 SQL 中有一个 INNER JOIN,您将不得不使用它两次,但它仍然有效。

使用临时字符串变量来存储临时输出,如下所示:

Dim tmp as String
tmp = Cstr(DLookup("tbl_MoPo_BM.MandateType_ID","tbl_MoPo_BM","tbl_MoPo_BM.MoPo_BM_ID = " & iMandate)) 'This is to fetch the ID you performed the inner join on
HasBM = DLookup("tbl_Mandate_Type.BM_Included","tbl_Mandate_Type","Mandate_Type_ID =" & tmp) ' this is to get your value

使用您的 DoCmd.RunSQL 是不够的,因为它仅用于操作查询(INSERTDELETEUPDATE)并且无法 return结果。

或者,您可以在 SQL 查询中使用 Recordset 来获取您想要的内容,但这需要更多工作,而 DLookup 旨在完全避免对单列 return 选择执行此操作。