附加数据以通过循环从Excel VBA访问

时间:2018-06-25 10:28:43

标签: excel vba loops ms-access adodb

想知道是否可以帮忙。我在Excel上填充了一个表,该表的长度没有确定(随着人们添加到表中而增加)。需要通过使用Excel中的按钮将这种不确定的数据量添加到Access中的数据库中。我制作了以下代码来尝试缓解这种情况,但得到

  

运行时错误'3709':连接不能用于执行此操作。在这种情况下,它是关闭的或无效的。

当我打开调试时,它指向以下行:

  

rs.Open sqlstr,DBCont

这可以在下面的代码中找到:

Sub submittoDB()
    Dim DBCont As Variant
    Set DBCont = CreateObject("ADODB.connection")
    Dim StrDBPath As String
    StrDBPath = "PATH Here\Database1.accdb"
    Dim sConn As String
    sConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=" & StrDBPath & ";" & _
        "Jet OLEDB:Engine Type=5;" & _
        "Persist Security Info=False;"
    DBCont.Open sConn
    MsgBox "Open DB"
    Dim rs As Object
    Set rs = CreateObject("ADODB.Recordset")
    Dim sqlstr As String
    Dim endlimit As Integer
    Dim i As Integer
    endlimit = Cells(Rows.Count, "H").End(xlUp).Row + 1
    'need to loop each line and remove test
    For i = 5 To endlimit
        sqlstr = "INSERT INTO DigiFinTracker (ProjectNo, ProjectName, Client, Tool, SuggAct, PercSav,PreDigCost,SuggSave,PropSav) VALUES ('" & Cells(6, 4) & "', '" _
        & Cells(5, 4) & "', '" & Cells(4, 4) & "', '" & Cells(i, 8) & "', '" & Cells(i, 9) & "', '" & Cells(i, 10) _
        & "', '" & Cells(i, 11) & "', '" & Cells(i, 12) & "', '" & Cells(i, 13) & "')"
        rs.Open sqlstr, DBCont
        DBCont.Close
    Next i
    DBCont.Close
End Sub

很抱歉,如果答案很简单,或者我错过了一些关键的事情,我似乎无法弄清问题出在哪里以及是否有可能循环这种类型的过程。

非常感谢您的提前答复!

1 个答案:

答案 0 :(得分:1)

在循环中,您将在每次迭代-DBCont.Close上关闭连接。因此,它不适用于第二次迭代。

从循环中删除DBCont.Close(建议),或者每次都打开它,然后在循环之前删除DBCont.Open sConn

For i = 5 To endlimit
    DBCont.Open sConn   'It would work better if you delete this line
    sqlstr = "INSERT INTO DigiFinTracker (ProjectNo, ProjectName, Client, Tool, SuggAct, PercSav,PreDigCost,SuggSave,PropSav) VALUES ('" & Cells(6, 4) & "', '" _
    & Cells(5, 4) & "', '" & Cells(4, 4) & "', '" & Cells(i, 8) & "', '" & Cells(i, 9) & "', '" & Cells(i, 10) _
    & "', '" & Cells(i, 11) & "', '" & Cells(i, 12) & "', '" & Cells(i, 13) & "')"
    rs.Open sqlstr, DBCont  
    DBCont.Close        'And delete this line as well
Next i

要查看导致数据不匹配的原因,请尝试以下操作:

sqlstr = "INSERT INTO DigiFinTracker (ProjectNo, ProjectName, Client, Tool, SuggAct, PercSav,PreDigCost,SuggSave,PropSav) VALUES ('" & Cells(6, 4) & "', '" _
& Cells(5, 4) & "', '" & Cells(4, 4) & "', '" & Cells(i, 8) & "', '" & Cells(i, 9) & "', '" & Cells(i, 10) _
& "', '" & Cells(i, 11) & "', '" & Cells(i, 12) & "', '" & Cells(i, 13) & "')"
 Debug.Print sqlstr
  • 看看立即窗口( Ctrl + G 打开);
  • 从此处复制SQL语句;
  • 将其粘贴到Access和work中,直到从查询中获得一些结果为止;