2017-03-02 38 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