我目前正在创建一个脚本,它将将指定文件夹中的所有Excel表单导入到Microsoft Access中的唯一表中。现在,这个过程应该每月或每两个月进行一次,这些excel表单上的标题经常变化。我试图使用DoCmd.Transferspreadsheet方法,但我遇到的问题是这些字段与目标表不匹配。现在,我不能只使用适当的字段名称来创建表格,然后导入到表格中,因为正如我所说,excel文件的标题经常变化。将Excel导入到Access中,动态获取列标题
我想要一种方法来导入一个Excel表格到一个新表格中,并且该表格应该自动采用Excel表格的字段,而不管它们是什么。因此,基本上每次我导入时,都应该使用适当的字段创建一个新表。
我唯一的解决方法是创建一个新的表格,每次我导入并循环查找excel文件的第一行以查找字段的名称,然后在创建表格时使用该表格。
但这是一个混乱的解决方法。我知道可以使用微软访问用户界面导入到全新的表格中。它需要点击几下,然后它的一切都很好。
我想要一个编程解决方案。
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标题后面逐行插入。 – PKatona
我可能不理解,但如果您在[TransferSpreadsheet](https://msdn.microsoft.com/en-us/library/office/ff844793.aspx)的表参数中指定一个不存在的表名并指定* True *用于列标题,MS Access用Excel文件的标题精确地导入电子表格。 – Parfait