使用 VBA 访问查询和报告?

Posted

技术标签:

【中文标题】使用 VBA 访问查询和报告?【英文标题】:Access queries and reporting with VBA? 【发布时间】:2016-01-13 21:33:31 【问题描述】:

我为报告创建了一些查询。我正在尝试编写一些 VB 代码,以便能够从查询中的数据创建一个记录集,并使用该数据填充 tbl_TempTable。

我的桌子是:

tbl_TempTable 
CompanyID     CompanyName     UnitPrice
-------------------------------------------

我的 qryCompanyInfo 的列与上表相同,但显然每列填充了 30 条左右的记录。

这是我目前的代码:

dim rs as dao.recordset
dim db as dao.recordset
dim db = currentDB()
dim x as integer

Set rs = db.openrecordset("qryCompanyInfo")
z=rs.recordcount
msgbox z

这里发生的情况是只选择了 1 条记录。为什么要这样做,应该选择大约 30 条记录?在选择数据之前是否需要先执行查询?我还将如何使用从 qry 中提取的数据填充我的 tbl_TempTable?

【问题讨论】:

【参考方案1】:

根据您是要从查询中插入新表还是现有表,总有“SELECT INTO”或“INSERT INTO”,但以 VBA 代码为指导。 . .

我不确定您的代码中的某些行 - 有两个变量(x 和 z),只有一个声明了,所以我认为这些是同一件事,我认为您想调用它记录集中的许多记录。还有两次奇怪的“db”声明。

这是我用来将查询结果复制到表中的一种方法,以及一些 cmets 来解释什么是什么:

' declare two recordsets - one for the query, one for the target table
Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset

' declare a string which will house your SQL statement
Dim SQL As String

' specify your SQL statement here
SQL = "SELECT * FROM table WHERE conditions"

' set the two recordsets to the query and the target table
Set rs1 = CurrentDb.OpenRecordset(SQL)
Set rs2 = CurrentDb.OpenRecordset("tbl_TempTable")

' step through the query results, one record at a time
' for each entry, copy that info to the 2nd recordset
' stop at End Of File
With rs1
While Not .EOF
    rs2.AddNew
    rs2("CompanyID") = rs1("CompanyID")
    rs2("CompanyName") = rs1("CompanyName")
    rs2("UnitPrice") = rs1("UnitPrice")
    rs2.Update
    .MoveNext
Wend
End With

【讨论】:

是的 x 和 z 应该被声明为整数。谢谢,这解决了我的问题。

以上是关于使用 VBA 访问查询和报告?的主要内容,如果未能解决你的问题,请参考以下文章

使用 vba 在访问查询中传递参数值

一天摘要的 VBA 访问查询

每天使用新数据刷新/更新/重新查询访问报告

生成 PDF 报告的 VBA 代码

MS Access 报告“每个细节”格式化和 VBA 中的访问

访问:如何执行查询并将其结果保存在报告中