【问题标题】:Import Excel into Access, get column headers dynamically将 Excel 导入 Access,动态获取列标题
【发布时间】:2016-04-29 15:13:23
【问题描述】:

我目前正在创建一个脚本,它将指定文件夹中的所有 Excel 工作表导入到 Microsoft 访问中的唯一表中。现在,问题是这个过程应该每月或每两个月完成一次,并且这些 Excel 表上的标题经常变化。我尝试使用 DoCmd.Transferspreadsheet 方法,但我遇到的问题是字段与目标表不匹配。现在,我不能只用适当的字段名称制作一个表格,然后导入其中,因为正如我所说,excel 文件的标题经常更改。

我想要一种将 Excel 工作表导入新表格的方法,该表格应自动采用 Excel 工作表的字段,无论它们是什么。所以基本上每次我导入时,都应该使用适当的字段创建一个新表。

我唯一的解决方法是每次导入时创建一个新表并循环遍历 excel 文件的第一行以查找字段的名称,然后在创建表时使用这些名称。

但这是一个混乱的解决方法。我知道可以使用 microsoft access UI 导入一个全新的表。它需要点击几下,然后一切都很好。

我想要一个程序化的解决方案。

Function loadData()

    Dim strPathFile As String, strFile As String, strPath As String
    Dim 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 = "C:\Bdz outputs\"

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

    strFile = Dir(strPath & "*.xlsx")
    strTable = Left(strFile, 8)
    strPathFile = strPath & strFile
    'Debug.Print (createTable("hello", "asdasd"))

    Do While Len(strFile) > 0
        strPathFile = strPath & strFile
        DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "Table1", strPathFile, False

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

        'Kill strPathFile

        strFile = Dir()

    Loop

End Function

【问题讨论】:

  • 如果您找不到使用 TransferSpreadsheet 的方法,您可以编写代码来打开和读取 Excel 电子表格。可以通过编程方式或其他选项更改标题名称,如果 excel 列值类型始终与访问列类型匹配,您可以保留访问名称并在 excel 标题之后逐行插入。
  • 我可能不明白,但如果您在 TransferSpreadsheet 的表参数中指定一个不存在的表名并为列标题指定 True,MS Access 将导入电子表格与 Excel 文件的标题完全一致。

标签: excel vba ms-access


【解决方案1】:

一种可能的解决方案是使用指向 Excel 数据的“动态”链接,例如,

CurrentDb.Execute _
        "SELECT * INTO myNewTable " & _
        "FROM [Excel 12.0 Xml;HDR=YES;IMEX=2;ACCDB=YES;DATABASE=C:\Users\Gord\Desktop\foo.xlsx].[Sheet1$]", _
        dbFailOnError

或者,正如 Parfait 在上面的评论中所建议的那样,这似乎也有效......

DoCmd.TransferSpreadsheet _
        TransferType:=acImport, _
        SpreadsheetType:=acSpreadsheetTypeExcel12Xml, _
        TableName:="myNewTable", _
        FileName:="C:\Users\Gord\Desktop\foo.xlsx", _
        HasFieldNames:=True

... [myNewTable] 尚不存在。

【讨论】:

    【解决方案2】:

    链接电子表格并阅读标题:

    DoCmd.TransferSpreadsheet acLink, acSpreadsheetTypeExcel12, "xlsTable1" , strPathFile, True 
    

    然后你可以循环链接表的字段来读取字段名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-15
      • 2012-06-20
      • 2018-11-12
      • 2016-01-11
      • 1970-01-01
      • 2010-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多