2014-02-16 134 views
0

有人可以看一下stSQL字符串,並幫助我修復與UPDATE語句關聯的語法錯誤嗎?使用VBA中的UPDATE SQL語句更新Access數據庫

運行時錯誤'-2147217900(8004e14)':UPDATE語句中的語法錯誤。

我對SQL有一個基本的理解,似乎並不瞭解我出錯的地方。

如果FileName UserForm值與Access Db中的FileName字段匹配,我想更新表1的字段。

感謝

Public Sub UpdateDatabaseEntry() 

Dim cn As New ADODB.Connection 
Dim rs As New ADODB.Recordset 
Dim stDB As String, stSQL As String, stProvider As String 
Dim FileName As String 
Dim Nickname As String 
Dim RecipientName As String 
Dim RecipientRelationship As String 
Dim Summary As String 
Dim Noteworthy As String 
Dim PreparedBy As String 

FileName = UserForm1.FileNameTextBox.Text 
Nickname = UserForm1.NicknameTextBox.Text 
RecipientName = UserForm1.RecipientNameTextBox.Text 
RecipientRelationship = UserForm1.RecipientRelationshipComboBox.Text 
Summary = UserForm1.SummaryTextBox.Text 
Noteworthy = UserForm1.NoteworthyCheckBox.Value 
PreparedBy = UserForm1.PreparedByTextBox.Text 

stDB = "Data Source= E:\MyDb.accdb" 
stProvider = "Microsoft.ACE.OLEDB.12.0" 

//Opening connection to database 
With cn 
    .ConnectionString = stDB 
    .Provider = stProvider 
    .Open 
End With 

//SQL Statement telling database what to do 
stSQL = "UPDATE Table1" & _ 
     "SET Nickname= '" & Nickname & "', RecipientName= '" & RecipientName & "', " & _ 
      "RecipientRelationship= '" & RecipientRelationship & "', Summary= '" & Summary & "', " & _ 
      "Noteworthy= '" & Noteworthy & "', PreparedBy= '" & PreparedBy & "', " & _ 
     "WHERE FileName= '" & FileName & "'" 

cn.Execute stSQL 

cn.Close 
Set rs = Nothing 
Set cn = Nothing 

End Sub 
+0

一般來說,當你遇到這樣的問題時,只需在執行SQL之前執行'Debug.Print stSQL'即可。這樣,您可以在即時窗口中看到SQL的具體內容,並幫助您查找任何語法錯誤。 – Yawar

回答

2

至少有一個問題是缺乏查詢空間所致。所以你的查詢開始UPDATE Table1set

stSQL = "UPDATE Table1 " & _ 
     "SET Nickname= '" & Nickname & "', RecipientName= '" & RecipientName & "', " & _ 
      "RecipientRelationship= '" & RecipientRelationship & "', Summary= '" & Summary & "', " & _ 
      "Noteworthy= '" & Noteworthy & "', PreparedBy= '" & PreparedBy & "'" & _ 
     "WHERE FileName= '" & FileName & "'" 

如果這不能解決問題。然後在變量替換之後用stSQL的值編輯您的問題。

編輯:

作爲TS所指出的,另一個問題是前,where(上述固定)。

+1

問題是在'Where'之前的逗號 –

+0

@ T.S。 。 。 。是的,這會成爲另一個問題。 –

+0

謝謝! 'WHERE'之前的','之後的逗號實際上是我的問題。一切正常! – blahblahblah

相關問題