简体   繁体   中英

Excel VBA Access

I have the following code, where .Fields... is not getting executed. Loop is directly closing the connection without adding records into table.

Code:

Sub insertIntoTable()

    Dim moviesConn As ADODB.Connection
    Dim moviesData As ADODB.Recordset
    Dim moviesField As ADODB.Fields
    Dim r As Range

    Set moviesConn = New ADODB.Connection
    Set moviesData = New ADODB.Recordset

    moviesConn.ConnectionString = conStrAccess
    moviesConn.Open

    On Error GoTo closeConnection

    With moviesData
        .ActiveConnection = moviesConn
        .Source = "tblFilmDetails"
        .LockType = adLockOptimistic
        .CursorType = adOpenForwardOnly
        .Open

    On Error GoTo closeRecordset
        For Each r In Range("A3", Range("A2").End(xlDown))
            .AddNew
            .Fields("Title").Value = r.Offset(0, 1).Value
            .Fields("Release_Date").Value = r.Offset(0, 2).Value
            .Fields("Length").Value = r.Offset(0, 3).Value
            .Fields("Genere").Value = r.Offset(0, 4).Value
            .Update
        Next r
    End With

    closeRecordset:
    moviesData.Close

    closeConnection:
    moviesConn.Close

End Sub

Please suggest

I was able to get your code to work using this connection string:

"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\best buy\\Desktop\\test.accdb;Persist Security Info=False;"

We can rule out data mismatch error because it throws a 3219 Runtime Error Operation before closing the connection.

在此处输入图片说明

Range("A3", Range("A2").End(xlDown)) should probably be changed Range("A2", Range("A" & Rows.Count).End(xlup)) for two reasons:

  1. It skips row 2
  2. If there is no data beyond row 2 you will add 1048575 empty records (Ask me how I know)

If you have a large dataset you should comment out .Update and use .UpdateBatch after you have added all the records. This will greatly improve performance.

    For Each r In Range("A3", Range("A2").End(xlDown))
        .AddNew
        .Fields("Title").Value = r.Offset(0, 1).Value
        .Fields("Release_Date").Value = r.Offset(0, 2).Value
        .Fields("Length").Value = r.Offset(0, 3).Value
        .Fields("Genere").Value = r.Offset(0, 4).Value
        '.Update
    Next r
    .UpdateBatch

在此处输入图片说明 Note: If you have the table open while adding the records then you have to press F5 to refresh the table and view the new data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM