VBA将数据写入Access数据库

时间:2014-12-09 22:46:06

标签: database vba

我收到错误消息

  

插入语句

中的语法错误

如何解决此错误?

我的代码是:

 filePath = 1

 For filePath = 1 To 48
    Row = 6
    openFile = Application.ActiveWorkbook.Path & "\data\" & filePath & ".xls"
    Workbooks.Open (openFile)

    Sql = "insert into crimedata(reportYear, state, school, campus, dataLabel, dataValue) values(2011,'<S>','<U>',NULL,'<L>','<V>')"

    Sql = Replace(Sql, "<S>", Cells(2, 1).Value)

    Do Until Cells(Row, 1).Borders(xlEdgeBottom).LineStyle = 1
        Sql = Replace(Sql, "<U>", Cells(Row, 1).Value)
        Sql = Replace(Sql, "NULL", Cells(Row, 2).Value)
        ColumnCounter = 3

        Do Until ColumnCounter = 14

            Sql = Replace(Sql, "<L>", Cells(5, ColumnCounter).Value)
            Sql = Replace(Sql, "<V>", Cells(Row, 3).Value)
            cn.Execute Sql

我在最后一行代码cn.execute Sql收到错误。

1 个答案:

答案 0 :(得分:0)

Dim wb as Workbook, sht as worksheet
Const SQL_TEMPLATE As String = "insert into crimedata(reportYear, state, school, campus, " & _ 
                            " dataLabel, dataValue) values(2011,'<S>','<U>',NULL,'<L>','<V>')"

filePath = 1

For filePath = 1 To 48
    Row = 6
    openFile = Application.ActiveWorkbook.Path & "\data\" & filePath & ".xls"
    Set wb  = Workbooks.Open(openFile)
    Set sht = wb.Sheets(1)


    Do Until sht.Cells(Row, 1).Borders(xlEdgeBottom).LineStyle = 1

        ColumnCounter = 3

        Do Until ColumnCounter = 14

            Sql = Replace(SQL_TEMPLATE , "<S>", sht.Cells(2, 1).Value)
            Sql = Replace(Sql, "<U>", sht.Cells(Row, 1).Value)
            Sql = Replace(Sql, "NULL", sht.Cells(Row, 2).Value)
            Sql = Replace(Sql, "<L>", sht.Cells(5, ColumnCounter).Value)
            Sql = Replace(Sql, "<V>", sht.Cells(Row, 3).Value)
            cn.Execute Sql