VBA SQL ACCDB执行中的语法错误应为“ DELETE”,“ INSERT”,“ SELECT”,“ PROCEDURE”或“ UPDATE”

时间:2019-03-06 12:35:04

标签: sql vba ms-access access-vba

我想创建一个按钮来统计Outlook中的操作。

我有以下代码,但很遗憾,它无法正常工作:

Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Set conn = New ADODB.Connection

conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\UHD-GEOBAN\SPOC und Incident\Screenshots\Sven\VBA\statistik.accdb; Persist Security Info=False;"
conn.Open
'DB: ID; currentDate; spocmail; onlinebankingmail
conn.Execute ("IF (NOT EXISTS(select * from tbl_statistics WHERE currentDate = '" & Date & "'))BEGIN INSERT INTO tbl_statistics(currentDate, spocmail) VALUES('" & Date & "', '1') END ELSE BEGIN UPDATE tbl_statistics SET spocmail = spocmail + 1 WHERE currentDate = '" & Date & "' END")

我还想知道,是否有可能将长SQL语句放在VBA代码的多行中

感谢前进

1 个答案:

答案 0 :(得分:0)

Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Set conn = New ADODB.Connection

conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\UHD-GEOBAN\SPOC und Incident\Screenshots\Sven\VBA\statistik.accdb; Persist Security Info=False;"
conn.Open
set rs = new ADODB.Recordset
rs.open "Select * from tbl_statistics where currentdate = #" & format(date(),"dd mmm yyyy") & "#" ,conn
'unless you're in the US not specifying the date format will bite you
if rs.eof then 
     conn.execute "INSERT INTO tbl_statistics(currentDate, spocmail) VALUES('#" & format(Date,"dd mmm yyyy")  & "#', '1') 

else
   conn.execute "UPDATE tbl_statistics SET spocmail = spocmail + 1 WHERE currentDate = '#" & format(Date,"dd mmm yyyy" & "#"
end if