从Excel导入的数据未附加在Access中

时间:2016-01-29 14:46:01

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

尝试从Excel工作表导入数据并附加到Access表。它读取第一个值并将其追加,但由于某种原因,第二个值不会被解释为数据。

我认为这是data4变量的格式问题,或者是在qs行中调用它的方式。有什么帮助吗?

    Public Sub Import2(FileName As Variant)
    Dim wb As Object, ws As Object
    Dim xl As Object
    Set xl = CreateObject("excel.Application")
    Dim qs As String

    Dim oConn As Object
    Set oConn = CreateObject("adodb.connection")
    oConn.ConnectionString = "Provider=microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Robert\desktop\testMAF.xlsm; Extended Properties=Excel 12.0 XML; hdr=no" & ";"

    'Open workbook specified in previous procedure and import data from specified cells
    Set wb = xl.Workbooks.Open(FileName)
            Set ws = wb.worksheets("For Export")
            data1 = ws.cells(2, 1)
            Data2 = ws.cells(2, 2)
            Data3 = ws.cells(2, 3)
            Data4 = ws.cells(2, 4)
            'Continues to ...Data62 = ws.cells(2 , 62)


    'The following commented code works, entering a date into the Formdate field on the MAF table
    'qs = "INSERT INTO MAF (FormDate) VALUES (#" & data1 & "#)"

    'However, when I expanded it to include the second field (below)it will not enter the value into the table.
    'The locals window shows qs=...Values(#1/4/2010#,Postflight) which is what I want to append
    'but when qs is executed, I am prompted, "Enter Parameter Value for Postflight"


    qs = "INSERT INTO MAF (FormDate,SN) VALUES (#" & data1 & "#," & Data4 & ")"

    DoCmd.RunSQL (qs)


    End Sub

2 个答案:

答案 0 :(得分:1)

在文本值" Postflight" 之前和之后添加引号(Data4变量中包含的值)...

qs = "INSERT INTO MAF (FormDate,SN) VALUES (#" & data1 & "#,'" & Data4 & "')"
                                                            ^             ^

如果您使用变量来保存INSERT声明...

,则可以更轻松地解决问题
Dim strInsert As String
strInsert = "INSERT INTO MAF (FormDate,SN) VALUES (#" & data1 & "#,'" & Data4 & "')"
Debug.Print strInsert '<- view this in Immediate window; Ctrl+g will take you there
CurrentDb.Execute strInsert, dbFailOnError

但是,如果您切换到INSERT的参数查询,或者使用DAO.Recordset.AddNew将行添加到MAF表,则引用问题不会太痛苦。

这是一个Recordset示例(未经测试)......

Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("MAF", dbAppendOnly)
With rs
    .AddNew
    !FormatDate.Value = data1
    !SN.Value = Data4
    .Update
    .Close
End With

答案 1 :(得分:-1)

这个问题几乎可以肯定在Excel中。 Excel允许您在同一列中输入任何类型的数据(文本,数字,日期等)。 Access通过要求您定义数据类型来防止这种情况。清理Excel中的数据。另外,请考虑使用这些方法之一将数据从Excel移动到Access。

http://www.erlandsendata.no/english/index.php?d=envbadacexportado

http://www.erlandsendata.no/english/index.php?d=envbadacexportdao