VBA:循环遍历各种Excel文件并将列复制到主文件中[关闭]
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了VBA:循环遍历各种Excel文件并将列复制到主文件中[关闭]相关的知识,希望对你有一定的参考价值。
我需要VBA代码,它打开文件夹中的所有xlxs文件并复制每个文件的特定列,并将这些数据放入主表中。需要将所有数据复制到主表的第一列,并且应始终在下面添加新数据。
对于没有电源查询的旧版本,我试过这个,但它不起作用:-(
Sub LoopAllExcelFilesInFolder()
Dim lastRow As Integer
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & ""
End With
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
myExtension = "*.xls*"
myFile = Dir(myPath & myExtension)
Do While myFile <> ""
Set wb = Workbooks.Open(Filename:=myPath & myFile)
lastRow = Workbooks("SUMMARY.xlsm").Sheets("Sheet1").Cells(Rows.Count, 9).End(xlUp).Row
DoEvents
wb.Worksheets(1).Range(Cells(2, 6), Cells(150, 6)).Copy_ Workbooks("SUMMARY.xlsm").Worksheets("Sheet1").Range(Cells(lastRow + 1, 1), Cells(lastRow + 150, 1))
wb.Close SaveChanges:=True
DoEvents
myFile = Dir
Loop
ResetSettings:
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
答案
Excel 2016有一个新的,相当简单的工具,名为PowerQuery内置,非常适合这种事情,比VBA简单得多。有关示例,请参阅https://support.office.com/en-us/article/combine-files-in-a-folder-with-combine-binaries-power-query-94b8023c-2e66-4f6b-8c78-6a00041c90e4的Microsoft网站,或谷歌“合并文件”和“PowerQuery”,您将看到成千上万的教程,视频等等,以更详细地演示如何执行此操作。
以上是关于VBA:循环遍历各种Excel文件并将列复制到主文件中[关闭]的主要内容,如果未能解决你的问题,请参考以下文章