2014-02-05 135 views
2

我想將某些目錄下的所有Excel文件(具有不同的數據和列)導入到MS Access 2010數據庫中,爲每個文件創建新表格。我發現代碼導入到一個表中的文件:自動將不同的excel文件導入MS Access 2010表格

Option Compare Database 
Option Explicit 

Function DoImport() 

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:\Documents and Settings\myName\My Documents\Access Test\" 

' 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 

End Function 

但我需要每次創建新表。在VBA中可能嗎?

+0

回覆:「如果有人可以提供創建按鈕,模塊和運行的步驟示例,我會非常感激。」 - 哇。如果這不是「太寬泛」,我不知道*是什麼*。 –

+0

我一直在網上瀏覽足夠長的時間,但還沒有找到關於如何創建按鈕並將其與模塊鏈接的示例。我相信它不會花很長時間來快速指導。無論如何,我的主要問題是關於循環創建新表。 –

+0

你想如何命名新表? – HansUp

回答

3

我認爲,所有你需要做的是你做DoCmd.TransferSpreadsheet前更改目標表的名稱(strTable值)各一次。

在一個評論中,你說你想從工作簿文件名派生表名。而且,每次通過循環時,另一個變量(strFile)都包含文件名。所以我認爲你可以從該文件名剝離文件擴展名並將其用作Access表名。

這裏是一個演示如何可以做一個即時窗口例子...

strFile = "foo.xls" 
strTable = Left(strFile, Len(strFile) - 4) 
? strTable 
foo 

如果這種做法是合適的,修改的循環在你的VBA代碼這樣的(未經測試)的代碼片段。 ..

strFile = Dir(strPath & "*.xls") 
Do While Len(strFile) > 0 
    strPathFile = strPath & strFile 
    strTable = Left(strFile, Len(strFile) - 4) 
    DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _ 
     strTable, strPathFile, blnHasFieldNames 
    strFile = Dir() 
Loop 
+0

正是我想要的,那麼容易。非常感謝! –

1

我曾經是一個MOS Access 2003.現在大家都在使用2010,但很多東西都沒有改變。

當您執行手動導入或導出時,可以將佈局保存爲規範。

此過程可以通過宏自動執行。

查看下面的鏈接瞭解更多詳情和步驟。

http://office.microsoft.com/en-us/access-help/run-a-saved-import-or-export-operation-HA001226020.aspx?CTT=5&origin=HA001226307

至於其他的東西,按鈕,模塊等,請先閱讀在線幫助/文檔。

我們在這裏幫助,但不是爲你做的工作。

Ĵ

+0

好吧,編輯我的問題聽起來不太懇求:)謝謝你的鏈接,但仍然有一種方法來導入單個文件,覆蓋同一張表。 –

1

好吧,我不知道這是否是不可正對目前的辦公CU我的電腦的問題。

http://msdn.microsoft.com/en-us/library/office/ff192475(v=office.14).aspx

這裏是如何使用ImportExport宏的鏈接。用於宏部分。

我讀過,你必須信任的位置。所以我嘗試了我的位置c:\ msdn加上嚮導的默認值。

enter image description here

仍然無法有它的選擇上來。

我試着創建一個規範,看看是否需要一個選項來顯示,沒有骰子。

但是,有一個DoCmd.TransferText和DoCmd.TransferSpreadSheet。

兩者都將允許您導入。

創建一個函數。從宏(RunCode)調用該函數。另一種方法是創建一個主菜單表單。有一個按鈕。在單擊命令上,運行代碼。

請告訴我,如果你得到ImportExportData宏顯示。我認爲這是一個錯誤。我需要停止最新的累積更新並重試。

enter image description here

+0

從宏調用我的功能,它工作正常,感謝您的幫助! –

相關問題