通过Excel工作表更新Access数据库

时间:2016-04-25 06:31:26

标签: excel vba excel-vba access

我试图通过此代码更新Access中的表,但它显示错误消息“用户定义类型未定义”。如何解决这个问题呢?     在这里输入代码

Sub UpdateClick()
   Dim conn As ADODB.Connection
   Dim myRecordset As ADODB.Recordset
   Dim strConn As String
Dim s As String
Set s = "C:\Users\PC2\Documents\Database2.accdb"

   strConn = "Provider=Microsoft.Jet.OLEDB.4.0 Data Source=s"
Set strConn = New ADODB.Connection

   Set myRecordset = New ADODB.Recordset

   With myRecordset
      .Open "Select * from PersonInformation", strConn, adOpenKeyset, adLockOptimistic
      .Fields("ID").Value = Worksheets("Sheet1").Range("A2").Value
      .Fields("FName").Value = Worksheets("Sheet1").Range("B2").Value
      .Fields("LName").Value = Worksheets("Sheet1").Range("C2").Value
      .Fields("Address").Value = Worksheets("Sheet1").Range("D2").Value
      .Fields("Age").Value = Worksheets("Sheet1").Range("E2").Value
      .Update
      .Close
   End With

   Set myRecordset = Nothing
   Set conn = Nothing
End Sub

1 个答案:

答案 0 :(得分:0)

在我的评论之后,我注意到你的错误不仅仅是连接 将您的代码调整为以下示例 - https://www.connectionstrings.com/access/等网站将显示您的Access版本使用哪个字符串。

Sub FillArrayAccess()

    Dim oConn As Object
    Dim myRecordset As Object
    Dim sConn As String
    Dim s As String

    s = "C:\Users\PC2\Documents\Database2.accdb"

    'Your connection string will change depending on the Access version.
    sConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & s
    'sConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & s 'Access 2010

    Set oConn = CreateObject("ADODB.Connection")
    oConn.Open sConn

    Set myRecordset = CreateObject("ADODB.RecordSet")
    myRecordset.Open "PersonInformation", oConn, 1, 3, &H2

    With myRecordset
        .AddNew
        .Fields("ID").Value = Worksheets("Sheet1").Range("A2").Value
        .Fields("FName").Value = Worksheets("Sheet1").Range("B2").Value
        .Fields("LName").Value = Worksheets("Sheet1").Range("C2").Value
        .Fields("Address").Value = Worksheets("Sheet1").Range("D2").Value
        .Fields("Age").Value = Worksheets("Sheet1").Range("E2").Value
        .Update
        .Close
    End With

    Set myRecordset = Nothing
    Set oConn = Nothing

End Sub

修改:更新代码以使用原始海报数据。