如何使用Excel VBA插入Office 365 Access数据库

时间:2017-03-13 17:45:55

标签: excel-vba ms-access vba excel

我最近升级到Office 365,现在发现自己试图使用Excel Excel将Excel工作表插入Access数据库。这是我正在尝试使用的VBA代码:

Sub ExportDataToAccess()

    Dim cn As Object
    Dim strQuery As String
    Dim myDB As String
    Dim creditDate As Date
    Dim regionalTeam As String


    'Initialize Variables
    creditDate = Worksheets("Treasury").Range("E20").Value
    regionalTeam = Worksheets("Treasury").Range("e21").Value

    myDB = "Y:\Credit DB\Credit.accdb"

    Set cn = CreateObject("ADODB.Connection")

    With cn
        .Provider = "Microsoft.ACE.OLEDB.12.0"    'For *.ACCDB Databases
        .ConnectionString = myDB
        .Open
    End With

    strQuery = "INSERT INTO Credit ([creditDate], [regionalTeam]) " & "VALUES (""" & creditDate & """, " & regionalTeam & ");"

    cn.Execute strQuery
    cn.Close
    Set cn = Nothing

End Sub

当我运行此子例程时,收到以下错误消息:

运行时错误:没有为一个或多个必需参数指定值。

我已尝试向Google发送错误消息,但没有太多运气。谁能告诉我哪里误入歧途?我还确认creditDate和regionalTeam具有有效值。我应该补充一点,cn.Execute strQuery似乎是违规代码(突出显示)。

感谢您的意见。

1 个答案:

答案 0 :(得分:1)

格式化日期表达式:

strQuery = "INSERT INTO Credit ([creditDate], [regionalTeam]) VALUES (#" & Format(creditDate, "yyyy\/mm\/dd") & "#, " & regionalTeam & ");"

或者,如果团队是文本:

strQuery = "INSERT INTO Credit ([creditDate], [regionalTeam]) VALUES (#" & Format(creditDate, "yyyy\/mm\/dd") & "#, '" & regionalTeam & "');"