ado in excel, inserting records into access database

偶尔善良 提交于 2019-12-24 00:52:28

问题


First time asker, usually I can find the answer by searching, but my google-fu seems weak today.

I have an excel workbook connecting to an access 2003 database to insert usage records

The code i'm using is:

sdbpath = ThisWorkbook.Path & "\Data.mdb"
sCommand = "INSERT INTO Usage VALUES('" & Environ("Username") & "',#" & Now() & "#)"

Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command

dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=TestPass;"
dbCommand.ActiveConnection = dbCon

dbCommand.CommandText = sCommand
dbCommand.Execute

dbCon.Close

The code fails on the line dbCommand.Execute with run-time error '-2147217900 (80040e14)' : Automation error.

The database its trying to insert the record into contains one table, usage, with two columns - UserID and AccessDate, formatted as text and DateTime respectively.

The odd part is the connection string seems OK, since it fails after the connection is already open, yet if I take the sCommand value before the execute is run, then paste it into a query in access and execute that - it runs fine!

In case it was access struggling with the datetime format i've tried switching it to text (and the hashtags in the code) but that still fails. I've also tried specifying the column names too.

Can anyone shed some light on what i'm doing wrong? I've never had so much trouble with a very simple bit of SQL.

Thanks in advance!


回答1:


In Access we need to specify the field-names. Even so, I found that I needed to wrap the table-name in square brackets before it would insert:

sCommand = "INSERT INTO [Usage] (UName, SomeDate) VALUES ('" & Environ("Username") _
    & "',#" & Now() & "#)"


来源:https://stackoverflow.com/questions/17919696/ado-in-excel-inserting-records-into-access-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!