VBA中的数据库更新

时间:2015-06-25 15:47:02

标签: sql vba excel-vba ms-access excel

Sub uoload_data()
    Dim s(40) As Integer
    Dim Row As Integer
    Dim i As Integer
    i = 0
    For Row = 7 To 39
        s(i) = Sheets("Data").Cells(Row, 5).Value
        i = i + 1
    Next
    Dim cn As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Dim AppPath As String
    Set cn = CreateObject("ADODB.Connection")
    AppPath = Application.ActiveWorkbook.Path
    strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=C:\Users\devi\Desktop\Ability.accdb;"
    cn.Open strConnection
    strSql = "INSERT INTO MyTable Values ('" & s(0) & " ',    
    '" & s(1) & " ','" & s(2) & " ','" & s(3) & " ' )"
    Set rs = cn.Execute(strSql)
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
End Sub

我有40个领域的excel表。我想更新所有字段以访问数据库。将记录插入数据库我使用insert into语句。同时我需要将所有数组字段写入insert into语句。所以请帮我解释一下。

1 个答案:

答案 0 :(得分:1)

您可以在此使用Join()

strSql = "INSERT INTO MyTable Values ('" & Join(s, "','") & "')"

s()中的值是整数,但是您将值包装在单引号中,那么您的数据库列是文本类型吗?

如果它们是数字列,那么你应该删除单引号。