【问题标题】:Exporting Excel sheet to Access db macro将 Excel 工作表导出到 Access db 宏
【发布时间】:2016-04-18 10:38:52
【问题描述】:

经过一番搜索,我找到了一个宏,可以将 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"

我在cnn.Open 收到错误“错误 2147217843 工作组信息文件丢失”

【问题讨论】:

标签: excel ms-access macros vba


【解决方案1】:

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

Access 数据库有两种密码:

  1. 与个人 Access 安全用户帐户关联的密码
  2. 适用于数据库本身的密码,所有用户都必须提供该密码才能打开数据库

您的密码是第二种类型,但您的连接尝试将其视为第一种类型。

在连接字符串中使用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

【讨论】:

  • 按照建议链接中的建议切换到旧版加密后,错误消息消失了。现在弹出一个新错误:错误 3265(在集合中找不到项目)在 rst(cells...)
  • 当您收到该错误时,请检查 Cells(1, i).Value 给您的信息。在我看来,它与记录集中列的名称不匹配 (rst)。
  • 我怀疑原因是记录ID,它在数据库中但不在源文件中。我从数据库中删除了它,但仍然得到同样的错误。需要更多调查。
【解决方案2】:

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

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

【讨论】:

  • 这给出了相同的错误消息(路径更改为实际路径。我假设您暗示 .mdw 文件存储在 db 的同一位置)
  • 嗯,这只是一个例子。当然,您必须将路径更改为当前设置的路径。
  • 我的假设是否正确,或者 .mdw 文件可以存储在其他地方吗?我如何找到它?
  • 它可以在这里找到:C:\Users\username\AppData\Roaming\Microsoft\Access 但是我不相信它会与 accdb 文件一起使用, 只有 mdb 文件。所以指针指向汉斯的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
相关资源
最近更新 更多