将Excel工作表导出到Access db宏

时间:2016-04-18 10:38:53

标签: excel-vba ms-access macros vba excel

经过一些搜索后,我找到了一个宏来导出Excel工作表作为密码保护的Access数据库中的记录

Dim cnn As ADODB.Connection 'dim the ADO collection class
Dim rst As ADODB.Recordset 'dim the ADO recordset class
Dim dbPath
Dim i As Long


'add error handling
On Error GoTo errHandler:

'Variables for file path and last row of data
dbPath = ("\\serverpath\reporting.accdb")
'Initialise the collection class variable
Set cnn = New ADODB.Connection

cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath, , "password"

Set rst = New ADODB.Recordset 'assign memory to the recordset

rst.Open Source:="table", ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
Options:=adCmdTable

rst.AddNew
For i = 1 To 180
    rst(Cells(1, i).Value) = Cells(nextrow, i).Value
Next i
rst.Update

'close the recordset
rst.Close
' Close the connection
cnn.Close
'clear memory
Set rst = Nothing
Set cnn = Nothing

'communicate with the user
MsgBox " The data has been successfully sent to the access database"

'Update the sheet
Application.ScreenUpdating = True

On Error GoTo 0
Exit Sub
errHandler:

'clear memory
Set rst = Nothing
Set cnn = Nothing
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Export_Data"

我收到错误"错误2147217843缺少工作组信息文件"在cnn.Open

2 个答案:

答案 0 :(得分:0)

您可以尝试传递有关工作组文件的信息,但我相信它主要用于mdb文件:

Provider=Microsoft.Jet.OLEDB.12.0;Data Source=D:\Test\Test.accdb;User ID=Admin;Jet OLEDB:System database=D:\Test\System.mdw;

答案 1 :(得分:0)

该错误消息具有误导性。问题不在于MDW(工作组信息文件)。

Access数据库有两种类型的密码:

  1. 与各个Access安全用户帐户关联的密码
  2. 一个适用于数据库本身的密码,所有用户都必须提供该密码才能打开数据库
  3. 您的密码是第二种类型,但您的连接尝试将其视为第一种类型。

    在连接字符串中使用Jet OLEDB:Database Password选项。

    Dim strConnect As String
    strConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
        dbPath & ";Jet OLEDB:Database Password='password';"
    Debug.Print strConnect
    cnn.Open strConnect