2016-12-07 68 views
0

我有一個問題,我無法找到正確的代碼來執行此操作。所以我有一個主文件夾(C:\產品)與多個子文件夾對應不同的產品(C:\產品\巧克力,C:\產品\牛奶等等)。 每個子文件夾都有許多excel文件,但我只想導入名爲sells.xlxs的文件。每個子文件夾都有一個sells.xlxs,我想將所有的sells.xlxs導入一個訪問數據庫。訪問VBA從不同的子文件夾導入特定的Excel文件

編輯:對不起,我沒有上傳,我使用的代碼:

Sub Insert2() 
    Const cstrSheetName As String = "Weekly" 
    Dim strDir As String 
    Dim strFile As String 
    Dim strTableName As String 
    Dim MyPath As String 
    Dim i As Long 

    i = 0 
    MyPath = "C:\Products" 
    strTableName = "Sells" 
    If Left(MyPath, 1) <> "\" Then 
    strDir = MyPath & "\" 
    Else 
    strDir = MyPath 
End If 
    strFile = Dir(MyPath & "\Sells.XLSX") 
While strFile <> "" 
i = i + 1 
strFile = strDir & strFile 
Debug.Print "importing " & strFile 

    DoCmd.TransferSpreadsheet _ 
    TransferType:=acImport, _ 
    SpreadsheetType:=acSpreadsheetTypeExcel9, _ 
    TableName:=strTableName, _ 
    FileName:=strFile, _ 
    HasFieldNames:=True, _ 
    Range:=cstrSheetName & "$" 

    strFile = Dir() 

Wend 
    End Sub 

你認爲你能幫助我嗎?

非常感謝

+2

剛子這個網站是不是發現其他程序員做的工作您。 「來自http://stackoverflow.com/tour->」關注你面臨的實際問題的問題,包括你已經嘗試過的內容以及你正在嘗試做什麼的細節。「 (...)「不要問......你沒有試圖找到答案的問題(顯示你的工作!)」 – CyberClaw

+0

你是對的。我完全忘記了我正在使用的代碼。我已經更新了 –

+0

有很多線程可以在這裏得到在這裏遞歸地鑽取目錄的例子。 – Lybren

回答

1
Dim FileSystem As Object 
Dim HostFolder As String 

HostFolder = MyPath 

Set FileSystem = CreateObject("Scripting.FileSystemObject") 
DoFolder FileSystem.GetFolder(HostFolder) 

Sub DoFolder(Folder) 
    Dim SubFolder 
    For Each SubFolder In Folder.SubFolders 
     Dim File 
     For Each File In Folder.Files 
      ' Operate on each file 
     Next 
    Next 

End Sub 

代碼信貸Rich,重排代碼,因此它不會遞歸迭代所有子文件夾中,MyPath

相關問題