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

标签 vba ms-access-2010

我需要创建一个独立的函数来检查一个值是真还是假。我试图设置一个执行此操作的 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 我最终得到了两个有效的解决方案:

DLOOKUP 解决方案 在我实现它时由 Magisch 编写:
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为此访问 native 功能。因为你有一个 INNER JOIN在您的 SQL 中,您将不得不使用它两次,但它仍然可以工作。

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

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 旨在完全避免为单列返回选择执行此操作。

关于vba - 如何使用 VBA Access 将 SQL 查询结果传递给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34180873/

相关文章:

ms-access - 在 MS Access 中跳过 CSV 文件的前三行(使用 DoCmd?)

SQL:访问查询唯一满足多个条件

excel - 使用 ActiveX 表单控件避免 .Activate

vba - 保存并转到新记录后如何重置表单的格式

vba - 交换两个范围 VBA

Excel VBA 通知所有只读查看者更改

vba - 错误消息 : Impossible to create ACCDE, MDE 或 ADE

ms-access - 使用变量时 DLookup 不起作用?

javascript - 使用 JavaScript 函数自动化网页

vba - Excel VBA .Saveas() 函数保留格式