自动导入Excel文件

时间:2016-09-22 14:39:35

标签: vba ms-access

我正在尝试将保存在公共驱动器中的文件作为表导入Access数据库。

这是我到目前为止所做的。

Dim TimeStamp2 As String
TimeStamp2 = Month(Date) & "." & Day(Date) - 1 & "." & Year(Date)
Dim xlFile As String, shtName
xlFile = "Open Orders @ " & TimeStamp2 & ".xls"
shtName = "Current Open Orders"

DoCmd.TransferSpreadsheet aclimport, acSpreadsheetTypeExcel12, "Open Orders From Yesterday", "\\cletus\KNXGENDB$\Daily Order Bookings\Open Orders @ " & TimeStamp2 & ".xls", True, shtName & "!"

这是我得到的错误:

  

运行时错误2306:根据输出格式或Microsoft Access指定的限制,输出的行太多

2 个答案:

答案 0 :(得分:0)

尝试调暗“昨天打开订单”和文件路径等

这段代码对我来说也是一样的。如果它只是你正在做的一个文件,你可以忽略它。

Sub Import2()

    Dim strPathFile As String, strFile As String, strPath As String
    Dim strWorksheet As String, strTable As String
    Dim blnHasFieldNames As Boolean

    ' Change this next line to True if the first row in EXCEL worksheet
    ' has field names
    blnHasFieldNames = True

    ' Replace C:\Documents\ with the real path to the folder that
    ' contains the EXCEL files
    strPath = CurrentProject.Path & "\Folder\"

    ' Replace tablename with the real name of the table into which
    ' the data are to be imported
    strTable = "AccessTableNameGoesHere"

    strWorksheet = "DataSheet"

    strFile = Dir(strPath & "*.xls")
    Do While Len(strFile) > 0
          strPathFile = strPath & strFile
          DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
                strTable, strPathFile, blnHasFieldNames, strWorksheet & "$"

    ' Uncomment out the next code step if you want to delete the
    ' EXCEL file after it's been imported
    '       Kill strPathFile

          strFile = Dir()
    Loop

    MsgBox "Import Successful!"

End Sub

答案 1 :(得分:0)

以下是具体修复:

  1. 修复文件扩展名。在一个地方你将它作为“.xlsx”而在另一个地方,“。xls”
  2. 更正acImport的拼写(在您的代码中,拼写错误拼写为“aclImport”)
  3. 要在导入前删除该表,请尝试DoCmd.DeleteObject acTable, "Open Orders From Yesterday"
  4. 在同一行上标注多个变量的尺寸时,必须为每个变量提供变量类型,否则它将使用默认的Variant。所以在这种情况下你会写Dim xFile As String, shtName As String
  5. 您实际上并未使用xFile变量。您应该删除它或将其添加到DoCmd.TransferSpreadsheet行以避免混淆。
  6. 以下是一切:

    Dim TimeStamp2 As String
    TimeStamp2 = Month(Date) & "." & Day(Date) - 1 & "." & Year(Date)
    Dim shtName As String
    shtName = "Current Open Orders"
    
    'Delete the existing table
    DoCmd.DeleteObject acTable, "Open Orders From Yesterday"
    
    'Import the data, recreating the table
    DoCmd.TransferSpreadsheet aclimport, acSpreadsheetTypeExcel12, "Open Orders From Yesterday", "\\cletus\KNXGENDB$\Daily Order Bookings\Open Orders @ " & TimeStamp2 & ".xls", True, shtName & "!"
    

    一个问题:您的工作表名称是否真的是“当前未结订单!”?如果没有,您可能想要从DoCmd.TransferSpreadsheet aclimport, acSpreadsheetTypeExcel12, "Open Orders From Yesterday", "\\cletus\KNXGENDB$\Daily Order Bookings\Open Orders @ " & TimeStamp2 & ".xls", True, shtName & "!"

    的末尾删除感叹号