将Excel导入到Access中,dynamic获取列标题

我目前正在创build一个脚本,将在Microsoft Access中将指定文件夹中的所有Excel表单导入到唯一表中。 现在,这个过程应该是每月或每两个月进行一次,这些excel表格上的标题经常变化。 我试图使用DoCmd.Transferspreadsheet方法,但我遇到的问题是这些字段与目标表不匹配。 现在,我不能只使用适当的字段名称来创build表格,然后导入到表格中,因为正如我所说,excel文件的标题经常变化。

我想要一个方法来导入一个Excel表格到一个新的表格,并且表格应该自动地采用Excel表格的字段,不pipe他们是什么。 所以基本上每次我导入时,都应该使用适当的字段创build一个新表。

我唯一的解决方法是创build一个新的表,每次我导入和循环的Excel文件的第一行查找字段的名称,然后用于创build表。

但是这是一个混乱的解决方法。 我知道有可能使用微软访问用户界面导入一个全新的表格。 这需要点击几下,然后一切都很好。

我想要一个编程解决scheme。

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 

一个可能的解决scheme可能是使用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在上面的评论中所build议的那样,这似乎也起作用了。

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

… [myNewTable]尚不存在。

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

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

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