代码跳过Recordset输入,ADODB Excel VBA

时间:2017-06-16 19:40:16

标签: excel-vba access-vba ado vba excel

今天是YouTube和互联网淘汰日,我还没有弄清楚如何让这些代码发挥作用。它可以毫无问题地打开和关闭连接,但是当我尝试写入记录集时,它会完全跳过所有内容并关闭连接而不输入任何数据。

Const AccessConnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Vision\Database\BVAS.accdb;Persist Security Info=False;"

Private Sub BtnSave_Click()

    Dim DbConn As ADODB.Connection
    Dim Inventory As ADODB.Recordset
    Dim r As Range

    Set DbConn = New ADODB.Connection
    Set Inventory = New ADODB.Recordset

    DbConn.ConnectionString = AccessConnStr
    DbConn.Open
       On Error GoTo CloseConnection
        With Inventory
            .ActiveConnection = DbConn
            .Source = "T3Scaffold_Inventory"
            .LockType = adLockOptimistic
            .CursorType = adOpenKeyset
            .Open
            On Error GoTo CloseRecordset
        End With
            CountSheet.Activate
                'WTF, why does it skip this ? Research if and IF or Do WHILE statement will work here for so that only the Items with quantity >0 are sent to ACCESS
                    For Each r In .Range("A2", Range("A2").End(xlDown))

                            With Inventory
                                .AddNew
                                .Fields("ScaffoldID") = Range("ScaffoldID")
                                .Fields("ItemNumber") = Cells(i + 1, 1).Value
                                .Fields("Quantity") = Cells(i + 1, 3).Value
                                .Fields("WorktypeID") = Range("WorktypeID")
                                .Fields("RentStartDate") = Range("Date")
                                .Fields("OnRent?") = "Yes"
                                .Update
                            End With

                    Next r


CloseRecordset:
    Inventory.CancelUpdate
    Inventory.Close

CloseConnection:
    DbConn.Close

Set Inventory = Nothing
Set DbConn = Nothing


End Sub

谢谢大家。我希望这是一个超级复杂的解决方案大声笑。 -MC

1 个答案:

答案 0 :(得分:0)

而导致的错误
For Each r In .Range("A2", Range("A2").End(xlDown))

出错,On Error GoTo CloseRecordset

要像这样改变的代码

For Each r In Activesheet.Range("A2", Activesheet.Range("A2").End(xlDown))

For Each r In Range("A2", Range("A2").End(xlDown))