[英]MS Access - Writing SQL in VBA
背景
開發一個MS Access模塊,該模塊在觸發onClick()事件時執行SQL代碼。
碼
Dim sqlString As String
sqlString = "SELECT [Table - Summary - All Item Forecasts, Sales, and POs].[COMPANY ID], " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[COMPANY NAME], " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].ITEM, " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].STYLE, " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].DESCRIPTION, " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[SALE PRICE], " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[ON-HAND QTY], " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[FORECAST QTY], " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[MaxOfLATEST PO DATE] " _
& "FROM [Table - Active Product Catalog] " _
& "LEFT JOIN [Table - Summary - All Item Forecasts, Sales, and POs] " _
& "ON [Table - Active Product Catalog].STYLE = [Table - Summary - All Item Forecasts, Sales, and POs].STYLE " _
& "GROUP BY [Table - Summary - All Item Forecasts, Sales, and POs].[COMPANY ID], " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[COMPANY NAME] , " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].Item, " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].Style, " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].Description, " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[SALE PRICE], " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[ON-HAND QTY], " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[FORECAST QTY], " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[MaxOfLATEST PO DATE]" _
& "HAVING ((([Table - Summary - All Item Forecasts, Sales, and POs].[COMPANY NAME]) Like ' * ' & [Enter Company Name:] & ' * '));"
DoCmd.RunSQL sqlString
錯誤
運行時錯誤'2342':RunSQL操作需要一個由SQL語句組成的參數。
問題
[Enter Company Name:]
”)。 我不太確定這是否會引發SQL語句,但是如前所述,該語法在MS Access中運行。 即使我用硬編碼值替換提示,也會收到相同的錯誤消息。 注意:我很可能會創建一個inputBox
,詢問company name
,然后將變量放在SQL語句的最后一行。
如DoCmd.RunSQL 文檔中所述,它用於運行“動作查詢”。 也就是說, SQLStatement是
字符串表達式,它是用於操作查詢或數據定義查詢的有效SQL語句。 它使用INSERT INTO,DELETE,SELECT ... INTO,UPDATE,CREATE TABLE,ALTER TABLE,DROP TABLE,CREATE INDEX或DROP INDEX語句。
請注意,以上列表包括SELECT...INTO
但不包括普通的SELECT
。 要執行普通的SELECT
並返回記錄集,您需要執行以下操作
Dim cdb As DAO.Database
Set cdb = CurrentDb
Dim rst As DAO.Recordset
Set rst = cdb.OpenRecordset(sqlString, dbOpenSnapshot)
' loop through the Recordset contents
另外,在最后兩行中,您缺少... [MaxOfLATEST PO DATE]和HAVING之間的空格。 嘗試將其作為SQL運行時,它將失敗。
我自己打了幾次,因為我是VBA的新手-我總是在run命令后放一個debug.print SQLstring,因為這樣更容易在即時窗口中找到這些丟失的空格等。
HTH,珍妮
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.