2014-02-16 103 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

相关问题