我正在嘗試使用Excel中的數據對MS Access數據庫進行簡單的插入查詢。我正在使用帶硬編碼值的參數化查詢進行測試。直接在Access中運行查詢,但試圖通過VBA執行它會導致語法錯誤。該查詢當前將插入Access表中除自動生成的ID以外的每個字段。Excel - SQL'INSERT INTO'查詢語法錯誤
Sub Test_SQL()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim result
Dim id As Integer
Dim year As Integer
Dim month As String
Dim combocode As String
Dim credamt As Double
Dim qty As Integer
Dim itemcode As String
Dim sepbundleamt As Double
Dim prodname As String
'*********query variables********************
year = 2017
month = "July"
combocode = "COMBCOD1"
credamt = 420
qty = 21
itemcode = "ITEMCOD1"
sepbundleamt = 12
prodname = "Test Product"
'********open DB connection and execute insertion******
On Error GoTo ErrorHandler
Set conn = New ADODB.Connection
Set cmd = New ADODB.Command
With conn
.Provider = "Microsoft.ACE.OLEDB.12.0;"
.ConnectionString = [redacted]
.Open
End With
With cmd
.ActiveConnection = conn
.CommandType = adCmdText
.CommandText = "INSERT INTO SB_DSLR (Year, Month, ComboCode, CreditAmt, Qty, ItemCode, SepBundleAmt, ProductName) VALUES (?,?,?,?,?,?,?,?);"
End With
With cmd.Parameters
.Append cmd.CreateParameter("Year", adInteger, adParamInput, 4, year)
.Append cmd.CreateParameter("Month", adWChar, adParamInput, 10, month)
.Append cmd.CreateParameter("ComboCode", adWChar, adParamInput, 10, combocode)
.Append cmd.CreateParameter("CreditAmt", adDouble, adParamInput, 10, credamt)
.Append cmd.CreateParameter("Qty", adInteger, adParamInput, 10, qty)
.Append cmd.CreateParameter("ItemCode", adWChar, adParamInput, 8, itemcode)
.Append cmd.CreateParameter("SepBundleAmt", adDouble, adParamInput, 10, sepbundleamt)
.Append cmd.CreateParameter("ProductName", adWChar, adParamInput, 100, prodname)
End With
cmd.Execute
conn.Close
Set cmd = Nothing
Exit Sub
ErrorHandler:
MsgBox (Err.Number & ": " & Err.Description)
If conn.State = adStateOpen Then
conn.Close
End If
Set cmd = Nothing
End Sub
你能分享你得到的確切的錯誤信息嗎? – Mureinik
'-2147217900:INSERT INTO語句中的語法錯誤。' –
如果您打印您的cmd文本,SQL會顯示什麼? –