【问题标题】:Using Access VBA, how to count number of output records in a select query and store the count as a VBA variable?使用 Access VBA,如何计算选择查询中的输出记录数并将计数存储为 VBA 变量?
【发布时间】:2017-03-19 07:01:53
【问题描述】:

我正在使用 Access 2013,特别是由于老板的指示,我无法使用 VBA 代码编辑器来最小化保存的查询和表 - 而且我无权修改表结构。

我有两个表:InvoiceDetails 和 AllItems,由 ItemID 连接。

INVOICEDETAILS     ALLITEMS
¯¯¯¯¯¯¯¯¯¯¯¯¯¯     ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
ItemID←-----------→ItemID
InvoiceNumber      Invoiced (Yes/No)

有时可以单独记入 InvoiceDetails 中的 Item,在这种情况下,将取消选中 AllItems 中对应的 Invoiced。我正在尝试比较

  • TotalItemCount = 给定InvoiceNumber“1”的Items 的数量

  • InvoicedItemCount = Items 的数量与给定的 InvoiceNumber “1”仍然是 Invoiced

对于第一个数字,我有

TotalItemCount = DCount("ItemID", "InvoiceDetails", "InvoiceNumber = 1")

对于第二个数字,我有一个 SELECT 查询,它提供了 SQL 中的计数,但我不知道如何将其转换为 VBA 变量 InvoicedItemCount

SELECT Count(InvoiceDetails.ItemID) 
FROM InvoiceDetails INNER JOIN AllItems 
     ON InvoiceDetails.LoadID = AllItems.LoadID 
WHERE InvoicedDetails.InvoiceNumber = 1 AND AllItems.Invoiced = True);

我知道DoCmd.RunSQL,但 AFAIK 只是运行查询并且没有提供可输出的整数以存储为 VBA 变量。有没有办法只在 VBA 中做到这一点?

【问题讨论】:

标签: sql vba ms-access


【解决方案1】:

我从 this question 获得了解决方案,我是由 Bernie 指导的。

假设 SQL 查询返回一条记录,只有一个字段,我们想要那个单一的值:

Dim rst As DAO.Recordset
Dim strSQL As String

strSQL = "SELECT x FROM y WHERE z=z;"
Set rst = CurrentDb.OpenRecordset(strSQL)

VariableName = rst.Fields(0)

rst.Close
Set rst = Nothing

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    相关资源
    最近更新 更多