复制文件夹中所有文件的数据

时间:2012-10-12 16:05:28

标签: excel-vba directory copy-paste vba excel

我需要打开文件夹中的所有Excel文件,并将每个文件中的第一行,第57行,第72行,第73行和第74行复制到同一工作簿中。

这就是我到目前为止所做的:

Dim i As Integer
Dim wbOpen As Workbook
Dim MyPath As String
Dim strFilename As String
MyPath = "C:\foldername" 'the folder
strFilename = Dir(MyPath & "\*.xls") 'all excel files in folder

Do Until strFilename = ""

    'here it gives an error, saying it can't open file,
    ' even though it apparently has found it
    wbOpen = Workbooks.Open(strFilename)

    'copy relevant text
    Workbooks(2).Activate
    Sheets("blad1").Rows(1, 57, 72, 73, 74).Copy
    Workbooks(1).Activate
    'select the first empty row
    irow = ActiveSheet.UsedRange.Rows.Count + 1
    'insert the copied
    irow.Insert Shift:=xlDown
    'close the workbook without saving
    Workbooks(2).Close SaveChanges:=False
    Close

Loop

1 个答案:

答案 0 :(得分:1)

以这种方式尝试:

MyPath = "C:\foldername" 'the folder
strFilename = Dir(MyPath & "\*.xls") 'all excel files in folder

Do Until strFilename = ""
...
strFilename=Dir()
Loop

告诉我这是否有效

编辑:修复Sheets("blad1").Rows(1, 57, 72, 73, 74).Copy Sheets("blad1").Rows("1, 57, 72, 73, 74").Copy