目标:将文件夹中保存的所有excel文件中的数据复制到主Excel文件中。正确复制数据。但是,我无法关闭程序读取的所有文件。已尝试过以下所有选项:ActiveWorkbook.Close
,Workbooks(MyFile).Close SaveChanges:=False
,Workbooks(MyFile).Close SaveChanges:=False
,但均无效。
如何解决问题?
VBA代码:
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
MyFile = Dir("C:\Desktop\Actual Files\")
Do While Len(MyFile) > 0
If MyFile = "zmaster.xlsm" Then
Exit Sub
End If
Workbooks.Open (MyFile)
Range("A2:O97").Copy
Windows("zmaster.xlsm").Activate
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1), Cells(erow, 15))
Application.ScreenUpdating = False
MyFile = Dir
Loop
End Sub
答案 0 :(得分:0)
创建工作簿变量并使用它是一种干净的方法。本子程序中激活工作簿并与未完全引用的工作表交互的方面是一个问题,您可以通过适当地引用它们来进一步改进它。
如果在子项中禁用它,也要小心application.screenupdating=false
,确保每个出口点都能恢复它。
Sub LoopThroughDirectory()
Application.ScreenUpdating = False
Dim MyFile As String, wbData As Workbook
Dim erow
MyFile = Dir("C:\Desktop\Actual Files\")
Do While Len(MyFile) > 0
If MyFile = "zmaster.xlsm" Then
Application.ScreenUpdating = True
Exit Sub
End If
Set wbData = Workbooks.Open(MyFile)
Range("A2:O97").Copy
Windows("zmaster.xlsm").Activate
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1), Cells(erow, 15))
wbData.Close False
MyFile = Dir
Loop
Application.ScreenUpdating = True
End Sub