[英]Import multiple Excel file and worksheets to Access, when not all Excel files have the same sheets
[英]Import identical excel files into access with multiple worksheets
因此,我正在嘗試尋找方法來促進使用Access重新組合Excel工作表中的數據。 我正在嘗試做的是,將多個格式完全相同的Excel文件合並到一個連續的表中。 現在,我有一個VBA函數,該函數使我可以跨一個excel文件目錄定位一個excel工作表,並將它們組合到一個訪問表中。 我的問題是,我該如何做同樣的事情,但是對於目錄中的每個工作表都是一槍而過,而不是為每個工作表運行和修改代碼。
TL; DR您有100個excel文件,每個文件中包含7個工作表。 格式相同,但是數據不同。 如何獲取全部100個文件並將其工作表合並到7個相應的MS Access表中?
******問題已解決。 如下工作代碼*******
名為SingleModule的模塊1:
Option Compare Database
Public Function importExcelSheets(Directory As String, TableName As String, WkShtName As String) As Long
On Error Resume Next
Dim strDir As String
Dim strFile As String
Dim I As Long
I = 0
If Left(Directory, 1) <> "\" Then
strDir = Directory & "\"
Else
strDir = Directory
End If
strFile = Dir(strDir & "*.XLSX")
While strFile <> ""
I = I + 1
strFile = strDir & strFile
Debug.Print "importing " & strFile
DoCmd.TransferSpreadsheet acImport, , TableName, strFile, True, WkShtName
strFile = Dir()
Wend
importExcelSheets = I
End Function
名為MultipleModule的模塊2:
Public Function importMultipleExcelFiles(Directory As String) As Long
For x = 1 To 7
Dim TableName As String
Dim WkShtName As String
TableName = Choose(x, "Table1", "Table2", "Table3", "Table4")
WkShtName = Choose(x, "Table1!", "Table2!", "Table3!", "Table4!")
Call SingleModule.importExcelSheets(Directory, TableName, WkShtName)
Next x
End Function
在立即窗口中使用以下命令來執行(確保更改了文件路徑):
? importMultipleExcelFiles("C:\Excel File Directory")
邊注:
您可以在立即窗口的SingleModule上使用以下命令來定位一個工作表:
? importExcelSheets("C:\FilePath", "TableName", "WkShtName!")
抱歉,我沒有看到您的TableName如何進入過程。 調用importExcelSheets函數時,將FOR-NEXT與CHOOSE函數一起使用。
for x= 1 to 7
TableName = choose(x, "Table1", "Table2"...)
WkShtName = choose(x, "ContactDetails!", ...)
importExcelSheets Dir, TableName, WkshtName
next x
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.