使用 VBA 访问查询和报告?
Access queries and reporting with VBA?
我有一些为报告创建的查询。我正在尝试编写一些 VB 代码,以便能够根据查询中的数据创建一个记录集,并用该数据填充 tbl_TempTable。
我的 table 是:
tbl_TempTable
CompanyID CompanyName UnitPrice
-------------------------------------------
我的 qryCompanyInfo 与上面 table 具有相同的列,但显然每个列都填充了 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?
根据您是想从查询中插入新的 table 还是现有的 table,总是有 'SELECT INTO' 或 'INSERT INTO',但是从您的VBA 代码作为指南。 . .
我不确定您代码中的某些行 - 有两个变量(x 和 z),只有一个已声明,所以我认为它们应该是同一回事,而且我认为您想要从记录集中调用那么多记录。还有两次 'db' 的奇怪声明。
这是我用来将查询结果复制到 table 的方法,以及一些解释内容的注释:
' 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
我有一些为报告创建的查询。我正在尝试编写一些 VB 代码,以便能够根据查询中的数据创建一个记录集,并用该数据填充 tbl_TempTable。
我的 table 是:
tbl_TempTable
CompanyID CompanyName UnitPrice
-------------------------------------------
我的 qryCompanyInfo 与上面 table 具有相同的列,但显然每个列都填充了 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?
根据您是想从查询中插入新的 table 还是现有的 table,总是有 'SELECT INTO' 或 'INSERT INTO',但是从您的VBA 代码作为指南。 . .
我不确定您代码中的某些行 - 有两个变量(x 和 z),只有一个已声明,所以我认为它们应该是同一回事,而且我认为您想要从记录集中调用那么多记录。还有两次 'db' 的奇怪声明。
这是我用来将查询结果复制到 table 的方法,以及一些解释内容的注释:
' 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