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

时间:2015-12-09 14:10:03

标签: vba ms-access-2010

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

查询将始终只返回一条记录。

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

已更新

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

1 个答案:

答案 0 :(得分:4)

您可以使用本地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)并且无法返回结果。

或者,你可以在你的SQL查询中使用Recordset来获取你想要的东西,但这样做更多,DLookup旨在完全避免单列返回选择。