循环文件夹中的Excel文件并附加到宏工作簿

时间:2016-06-17 14:59:10

标签: excel vba excel-vba

我需要打开文件夹中的所有.xlsx文件,并将其内容复制到运行宏的工作簿中。由于this博客文章,代码从myExtension = "*.xls"更改为myExtension = "*.xlsx",我已经能够遍历文件夹中的所有Excel文件。但是,我无法弄清楚如何复制每个工作簿的工作表1的所有内容并将其粘贴到运行宏的ThisWorkbook中。

例如,在Do While循环中,上面博客文章中的代码执行此操作:

'Change First Worksheet's Background Fill Blue
  wb.Worksheets(1).Range("A1:Z1").Interior.Color = RGB(51, 98, 174)

但我想做这样的事情:

'Copy all the cells that have data in them and paste/append to VBA workbook
  wb.Worksheets(1).UsedRange.Copy ' this hasn't been working for me
  ThisWorkbook.Worksheets(1). (somehow get to the first empty row) . Paste

有什么想法吗?

顺便说一句,我复制的Excel文件都将在第一张表中包含数据,并且它们没有任何标题行。

2 个答案:

答案 0 :(得分:0)

iRow_Target = 0
(For Each Workbook in your directory)
Set Wb = Workbooks.Open(Wb_File_Name)
For Each Ws in Wb.Sheets
    For iRow = 1 to Ws.UsedRange.Rows.Count 'This gives you rows count
        Ws.Rows(iRow).Copy 
        iRow_Target = iRow_Target + 1 'This will have the last row saved
        Thisworkbook.Sheets("Target").Range("A" & iRow_Target).xlPasteAll 'You can use other xlPaste<options> based on your needs
    Next
Next

答案 1 :(得分:0)

with thisworkbook.worksheets(1)
  wb.worksheets(1).usedrange.copy .cells(.rows.count,1).end(xlup).offset(1)
end with