2013-02-19 58 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

相关问题