【发布时间】:2021-07-04 18:27:42
【问题描述】:
我在一个文件夹中有 3 个文件和一个主模板。
我想:
- 遍历这些文件,然后将内容复制到主文件。
- 每个 WHOLE 文件都将粘贴到主文件中的新工作表中。
- 新工作表的名称将与文件名相同。
以下代码不起作用,缺少功能 2 和 3。
Sub AllFiles()
Application.EnableCancelKey = xlDisabled
Dim folderPath As String
Dim Filename As String
Dim wb As Workbook
Dim sh As Worksheet
folderPath = "C:\Users\Ryan\Desktop\LoopThroughFolders\Sample1\" 'contains folder path
If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
Filename = Dir(folderPath & "*.xlsx")
Do While Filename <> ""
Application.ScreenUpdating = False
Set wb = Workbooks.Open(folderPath & Filename)
Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row).Copy
'Not working well here as it will be overwritten by the next file
Workbooks("Master Template").Worksheets("Sheet1").Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row + 1).PasteSpecial xlPasteValues
Workbooks(Filename).Close
Filename = Dir
Loop
Application.ScreenUpdating = True
End sub
【问题讨论】:
-
您可能会从中得到一些想法(我的 vba 不够好,无法纠正您的问题,抱歉):stackoverflow.com/questions/41644971/… 和 stackoverflow.com/questions/30575923/…
-
@Ryan 你试过我下面答案中的代码吗?是否按预期工作?
-
@Shai Rado 你太棒了!一切正常!!
标签: vba excel excel-2010