2013-02-19 37 views
-1

我期待獲得一些代碼,用於從文件夾中提取文件並將其中的數據粘貼到目標電子表格中。要從多個電子表格複製的宏

我有一個文件夾包含所有格式相同的報告,每週生成報告並每週保存到一個新文件夾中,因此我並不總是從同一文件夾中選擇文件。我想要一個提供'瀏覽文件夾'對話框的宏,然後當我選擇文件夾時,它依次打開該文件夾中的每個Excel文件,複製數據(範圍A:W),將其粘貼回目標電子表格,關閉電子表格,然後移動到文件夾中的下一個文件。

在報告中,標題下面的行數不總是相同的,可能只有1行或者可能有2+行,所以我還需要使用代碼來檢查數據是否存在於每行中,如果只有1行將複製該行,如果超過1行,它將複製所有行。

回答

1

可以使用通過文件夾這樣的循環在選定的文件夾:

Dim sPath As String 
Dim sFil As String 
Dim FolderPath As String 
    Dim diaFolder As FileDialog 

    ' Open the file dialog 
    Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker) 
    diaFolder.AllowMultiSelect = False 
    diaFolder.Show 
    FolderPath = diaFolder.SelectedItems(1) 

    ' Cycle through spreadsheets in selected folder 

sPath = FolderPath & "\" 'location of files 

sFil = Dir(sPath & "*.csv") 'change or add formats 
Do While sFil <> "" 'will start LOOP until all files in folder sPath have been looped  through 


Set oWbk = Workbooks.Open(sPath & "\" & sFil) 'opens the file 
' do something 

oWbk.Close True 
sFil = Dir 

Loop 

然後你可以把你的代碼複製列在那裏說:'do something

相關問題