【问题标题】:Loop through Excel Files in Folder and Append to Macro Workbook循环遍历文件夹中的 Excel 文件并追加到宏工作簿
【发布时间】:2016-06-17 14:59:10
【问题描述】:

我需要打开文件夹中的所有 .xlsx 文件并将其内容复制到运行宏的工作簿中。感谢this 博客文章,我已经能够遍历文件夹中的所有 Excel 文件,代码从myExtension = "*.xls" 更改为myExtension = "*.xlsx"。但是我不知道如何复制每个工作簿的工作表 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 文件都将在第一张表中包含它们的数据,并且它们不会有任何标题行。

【问题讨论】:

  • 请说明“这对我不起作用”;它会产生错误还是什么?
  • 另外,请查看此帖子至learn how to avoid using select 并复制粘贴...
  • this 会告诉你如何找到最后使用的单元格。
  • @vacip 好吧,我在 A1 单元格中创建了一个带有“一些数据”的 excel 文件,并将其放在我的目标文件夹中。然后当我运行宏时,我的剪贴板上什么都没有。

标签: vba excel


【解决方案1】:
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

【讨论】:

    【解决方案2】:
    with thisworkbook.worksheets(1)
      wb.worksheets(1).usedrange.copy .cells(.rows.count,1).end(xlup).offset(1)
    end with
    

    【讨论】:

    • 这看起来应该没有问题,但它不适合我。在调试中,程序打开目标文件,到达代码中的这一点,然后实际上没有任何内容被复制。不知道为什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 2012-04-25
    相关资源
    最近更新 更多