2017-03-02 74 views
0

这让我疯狂。我一直在反对将一些Excel数据导入微软访问。愚蠢的我认为这应该很容易,因为他们都是微软产品。将文件导入到Microsoft Access中:现场映射

有三个excel文件,每个约40MB。每个文件中有四个选项卡,每个选项卡在文件之间具有相同的字段顺序。即文件1中的选项卡A具有与文件2和文件3中选项卡A相同顺序的相同字段名称。并且访问数据库中的相应表格与完全相同的顺序中的字段名称完全相同。其他选项卡也一样。每个标签中约有90K行和约40列。

我直接导入到Access并创建一个新表的第一个选项卡。即使其他文件具有相同的布局,但我似乎无法正确导入其他文件。即使这些字段按照完全相同的顺序具有完全相同的名称,但它仍会使映射不断变化。

不是很严重,我得到一个或两个字段的类型转换错误(我也没有得到,因为访问表中的所有字段都是“短文本”类型,所以我可以只导入任何内容没有处理的数据文件)或文件中的一些错误源字段被导入到数据库中错误的目标字段中。

只有几个领域变得混乱起来,因为这意味着我必须检查整个表以确定事情是否发生,这几乎更令人讨厌。这并不一致,每次尝试时都会有所不同。

我试图从Excel文件导入数据,并通过将每个选项卡保存为csv。什么都没有跆拳道我做错了。很高兴尝试使用其他数据库(文件制作者等)。我不在乎使用访问权限,我只是认为它会更容易,但我不明白为什么这么困难。

回答

0

从文件夹中所有文件的所有工作表导入数据。

Dim blnHasFieldNames As Boolean, blnEXCEL As Boolean, blnReadOnly As Boolean 
Dim intWorkbookCounter As Integer 
Dim lngCount As Long 
Dim objExcel As Object, objWorkbook As Object 
Dim colWorksheets As Collection 
Dim strPath As String, strFile As String 
Dim strPassword As String 

' Establish an EXCEL application object 
On Error Resume Next 
Set objExcel = GetObject(, "Excel.Application") 
If Err.Number <> 0 Then 
     Set objExcel = CreateObject("Excel.Application") 
     blnEXCEL = True 
End If 
Err.Clear 
On Error GoTo 0 

' Change this next line to True if the first row in EXCEL worksheet 
' has field names 
blnHasFieldNames = False 

' Replace C:\MyFolder\ with the actual path to the folder that holds the EXCEL files 
strPath = "C:\MyFolder\" 

' Replace passwordtext with the real password; 
' if there is no password, replace it with vbNullString constant 
' (e.g., strPassword = vbNullString) 
strPassword = "passwordtext" 

blnReadOnly = True ' open EXCEL file in read-only mode 

strFile = Dir(strPath & "*.xls") 

intWorkbookCounter = 0 

Do While strFile <> "" 

     intWorkbookCounter = intWorkbookCounter + 1 

     Set colWorksheets = New Collection 

     Set objWorkbook = objExcel.Workbooks.Open(strPath & strFile, , _ 
      blnReadOnly, , strPassword) 

     For lngCount = 1 To objWorkbook.Worksheets.Count 
      colWorksheets.Add objWorkbook.Worksheets(lngCount).Name 
     Next lngCount 

     ' Close the EXCEL file without saving the file, and clean up the EXCEL objects 
     objWorkbook.Close False 
     Set objWorkbook = Nothing 

     ' Import the data from each worksheet into a separate table 
     For lngCount = colWorksheets.Count To 1 Step -1 
      DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _ 
        "tbl" & colWorksheets(lngCount) & intWorkbookCounter, _ 
        strPath & strFile, blnHasFieldNames, _ 
        colWorksheets(lngCount) & "$" 
     Next lngCount 

     ' Delete the collection 
     Set colWorksheets = Nothing 

     ' Uncomment out the next code step if you want to delete the 
     ' EXCEL file after it's been imported 
     ' Kill strPath & strFile 

     strFile = Dir() 

Loop 

If blnEXCEL = True Then objExcel.Quit 
Set objExcel = Nothing 

http://www.accessmvp.com/KDSnell/EXCEL_Import.htm#ImpAllWkshtsFilesSepTbls