2016-01-22 130 views
0

我目前正在创建一个脚本,它将将指定文件夹中的所有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 
+0

如果您无法通过TransferSpreadsheet找到一种方法,则可以编写代码来打开并阅读Excel电子表格。可以通过编程方式更改标题名称,或者另一个选项,如果excel列值类型始终与访问列类型匹配,则可以保留访问名称,并只需在Excel标题后面逐行插入。 – PKatona

+2

我可能不理解,但如果您在[TransferSpreadsheet](https://msdn.microsoft.com/en-us/library/office/ff844793.aspx)的表参数中指定一个不存在的表名并指定* True *用于列标题,MS Access用Excel文件的标题精确地导入电子表格。 – Parfait

回答

2

一个可能的解决方案可能是“对飞”链接到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 

,或者如芭菲提出上述评论,这似乎工作也...

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

...其中[myNewTable]尚不存在。

1

链接电子表格和读头:

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

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