我发现一个网站有一个宏,可以让你完成一个文件夹中所有电子表格的循环操作。我将此宏用作下面宏的基础:
See Link Here
我已经成功地将它用于其他一些项目,但是在我当前的项目中遇到了一些问题。我试图打开一个文件夹中的许多电子表格,复制数据,然后粘贴到主电子表格中。我们的目标是将许多电子表格中的所有数据放到一个单一的电子表格中。文件夹中许多电子表格的列表是一个随时间变化的动态列表。所以我不能简单地单独引用每个电子表格,这就是为什么我尝试使用上面链接的循环策略。
我遇到的问题是一些粘贴在以前电子表格的值上。因此,每个电子表格不是粘贴在前一个值的底部,而是粘贴在中间,覆盖我需要的信息。我想我的问题是,当我进入代码的row.count、copy/paste部分以及I&的变量时,excel会混淆应该引用哪个电子表格;j分配不正确。但我想不出怎么解决这个问题。我没有主意了,彻底的沮丧了!抱歉,如果我搞砸了一些相当基本的东西,但我是一个新的VBA。
Sub CombineReports()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim i As Integer
Dim j As Integer
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
myPath = "I:\Pricing\mt access\Tier Reports\Final Reports\"
'Target Path with Ending Extention
myFile = Dir(myPath)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Worksheet tasks
i = wb.Worksheets(1).Range("A" & Rows.Count).End(xlUp).Row
wb.Worksheets(1).Range("A5", "N" & i).Copy
Workbooks.Open ("I:\Pricing\mt access\Tier Reports\Final Reports\Combined Report\CombinedTierReport.xlsx")
j = Workbooks("CombinedTierReport.xlsx").Worksheets("AllStores").Range("B" & Rows.Count).End(xlUp).Row
Workbooks("CombinedTierReport.xlsx").Worksheets("AllStores").Range("A" & j + 1, "N" & i).PasteSpecial xlPasteValues
Workbooks("CombinedTierReport.xlsx").Save
Workbooks("CombinedTierReport.xlsx").Close
DoEvents
'Save and Close Workbook
Application.DisplayAlerts = False
wb.Close SaveChanges:=False
Application.DisplayAlerts = True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub