【发布时间】: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 文件的标题完全一致。