在后台运行查询

时间:2015-11-04 22:18:01

标签: ms-access access-vba ms-access-2010

我有一个我正在研究的数据库。它由拆分数据库组成,包括前端和后端表的多个链接。

我正在编写一份由15份不同的子报告组成的报告。我有一个表格,允许我输入报告的开始日期和结束日期。有一个生成最终报告的按钮。问题是当我想生成报告时,我将不得不为每个子报告重新运行每个不同的生成表查询。这个问题是每个查询会有2个警告,一个用于删除我的表,另一个用于添加到表中的行。

我在线研究并发现此代码运行执行命令,该命令将删除所有警告。我是VB的新手,但我想我会尝试一下,我得到以下运行时错误" 3078:MS Access数据库引擎无法找到输入表或查询" 。我检查了查询名称并且匹配,所以我不确定为什么我会收到此错误。我只尝试了15个查询中的一个,因此我可以确保它有效。一旦我开始工作,我的另一个问题是将所有这些组合成15个执行命令在模块中工作吗?

Private Sub PS_Report_Date_AfterUpdate()

Dim dbs As DAO.Database
Dim lngRowsAffected As Long
Dim lngRowsDeleted As Long
Dim sql$

sql = "[qry_Maui_Division_KWH_Produced]"

Set dbs = CurrentDb

' Execute runs both saved queries and SQL strings
dbs.Execute sql, dbFailOnError

' Get the number of rows affected by the Action query.
' You can display this to the user, store it in a table, or trigger an action
' if an unexpected number (e.g. 0 rows when you expect > 0).
lngRowsAffected = dbs.RecordsAffected

dbs.Execute "DELETE FROM tbl_Maui_Division_KWH_Produced WHERE Bad", dbFailOnError
lngRowsDeleted = dbs.RecordsAffected    
End Sub

SQL代码:

SELECT 
tbl_MPP_DailyGenerationReport.DateLog, 
[MPP_Daily_Gross_Gen_kWh]+[Total_Gross_kWh] AS Maui_Gross_kWh_Produced,
[Total_Aux]+[Total_Aux_kWh] AS Maui_Gross_Aux_kWh_Produced, [MPP_Daily_Gross_Gen_kWh]-[Total_Aux]+[Total_Net_kWh] AS Maui_Net_kWh_Produced, 
Round(([Total_MBTU_Burned]*1000000)/([MPP_Daily_Gross_Gen_kWh]+[Total_Gross_kWh]),0) AS Maui_Gross_BTU_kWh, 
Round([Total_MBTU_Burned]*1000000/([MPP_Daily_Gross_Gen_kWh]-[Total_Aux]+[Total_Net_kWh]),0) AS Maui_Net_BTU_kWh, 
Round(([MPP_Daily_Gross_Gen_kWh]+[Total_Gross_kWh])/[Total_Barrels_Burned],0) AS Maui_Gross_kWh_BBL, 
Round(([MPP_Daily_Gross_Gen_kWh]-[Total_Aux]+[Total_Net_kWh])/[Total_Barrels_Burned],0) AS Maui_Net_kWh_BBL 

INTO tbl_Maui_Division_KWH_Produced

FROM ((tbl_MPP_DailyGenerationReport 
INNER JOIN tbl_KPP_DailyGenerationReport 
ON tbl_MPP_DailyGenerationReport.DateLog = tbl_KPP_DailyGenerationReport.DateLog) 
INNER JOIN tbl_MPP_Aux_DailyGenerationReport 
ON tbl_MPP_DailyGenerationReport.DateLog = tbl_MPP_Aux_DailyGenerationReport.DateLog) 
INNER JOIN qry_Maui_Total_Fuel_Burned 
ON tbl_MPP_DailyGenerationReport.DateLog = qry_Maui_Total_Fuel_Burned.DateLog
WHERE (((tbl_MPP_DailyGenerationReport.DateLog)=[Forms]![Power Supply Reports]![PS_Report_Date]));​

1 个答案:

答案 0 :(得分:1)

这将在没有警告的情况下运行您的查询:

Private Sub PS_Report_Date_AfterUpdate()
    DoCmd.SetWarnings False
    DoCmd.OpenQuery "qry_Maui_Division_KWH_Produced"
    DoCmd.RunSQL "DELETE FROM tbl_Maui_Division_KWH_Produced WHERE Bad"
    DoCmd.SetWarnings True
End Sub