将多个Excel文件中的一个工作表导入到多个访问表中

我有大约200个Excel文件,我想导入到一个单一的Access数据库,并为每个文件有一个表。 每个Excel文件都有多个工作表,但是我想要导入的文件是一致的。

我已经find了一些代码,请参阅: http : //www.accessmvp.com/KDSnell/EXCEL_Import.htm#ImpBrsFldFiles,http : //social.msdn.microsoft.com/Forums/en-US/dfea25ab-cd49- 495℃-8096-e3a7a1484f65 /import-多Excel的文件与-不同的文件名,为存取使用,VBA

这是我尝试的代码片段之一:

Option Compare Database Sub ImportFromExcel() End Sub Dim strPathFile As String, strFile As String, strPath As String Dim strTable As String, strBrowseMsg As String Dim blnHasFieldNames As Boolean ' Change this next line to True if the first row in EXCEL worksheet ' has field names blnHasFieldNames = True strBrowseMsg = "C:\Users\fratep\Desktop\Long-term EWM Study Data Files\" strPath = BrowseFolder(strBrowseMsg) If strPath = "" Then MsgBox "No folder was selected.", vbOK, "No Selection" Exit Sub End If ' Replace tablename with the real name of the table into which ' the data are to be imported strTable = "tablename" strFile = Dir(strPath & "\*.xls") Do While Len(strFile) > 0 strPathFile = strPath & "\" & strFile DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _ strTable, strPathFile, blnHasFieldNames ' Uncomment out the next code step if you want to delete the ' EXCEL file after it's been imported ' Kill strPathFile strFile = Dir() Loop Sub ImportMultiExcels() End Sub 

从上面的第一个链接,但我似乎无法让他们做我在找什么。 谁能帮我?

我是VBA的新手,所以对编辑代码有点不确定。

看来您可以使用导入向导成功将工作表导入到Access中。 在这种情况下,您应该能够使用DoCmd.TransferSpreadsheet方法从Access数据库中的VBA代码执行相同的操作。

以下过程将名为XYZ Priority的单张表导入名为Import1的Access表。

我使用了一个常量作为工作表名称,因为您表示目标工作表在所有源工作簿文件中都具有相同的名称。

我构build了表名为“导入”i 。 将其扩展到多个工作簿时,可以在每次导入后增加i 。 或者你也许对表名有不同的策略; 你没有说。

我将TransferSpreadsheet语句分成几行,并将选项名称(希望)包括在内,以便于理解。

我的工作表包含列名,所以我有HasFieldNames:=True

而且我的工作簿是使用旧版本的Excel创build的。 SpreadsheetType:=acSpreadsheetTypeExcel9适用于此; SpreadsheetType可能需要一个不同的值

 Public Sub Demo_TransferSpreadsheet() Const cstrSheetName As String = "XYZ Priority" Dim i As Long Dim strFileName As String Dim strTableName As String ' my workbook is located in the same folder as the Access db file strFileName = CurrentProject.Path & Chr(92) & "temp.xls" i = 1 strTableName = "Import" & CStr(i) DoCmd.TransferSpreadsheet _ TransferType:=acImport, _ SpreadsheetType:=acSpreadsheetTypeExcel9, _ Tablename:=strTableName, _ FileName:=strFileName, _ HasFieldNames:=True, _ range:=cstrSheetName & "$" End Sub