VBA:打开多个文件并在所有打开的文件上执行宏
问题描述:
我想写一个宏,它将打开30个全部具有相同结构的excel文件。VBA:打开多个文件并在所有打开的文件上执行宏
宏应对所有文件执行操作,并从每个文件中获取结果并将其放入另一个excel文件中。这意味着:所有结果(值)都将被复制到目标文件中。
如何编写VBA代码以打开多个文件?
如何从每个文件中获取结果并将它们放在我的destination.xls文件中?
答
尝试检查出FileSearch.LookIn Property
修改例子类似的东西。 (这就要求所有的30个文件的一个文件夹中虽然)
Dim WrkBook as Workbook
Set fs = Application.FileSearch
With fs
.SearchSubFolders = False
.LookIn = "C:\My Documents" 'Path of folder to search
.FileName = "*.xls" 'Limit to excel files
If .Execute > 0 Then
Debug.Print "There were " & .FoundFiles.Count & " file(s) found."
For i = 1 To .FoundFiles.Count
WrkBook = Workbooks.Open(Filename:=.FoundFiles(i))
WrkBook.Worksheets(1).Select
ThisWorkbook.Worksheets(1).Cells(DestinationRange) = WrkBook.Worksheets(1).Cells(SourceRange).Value
Next i
Else
Debug.print "There were no files found."
End If
End With
您也可以尝试
Workbooks("Destination.xls").Worksheets("Sheet1").Cells(DestinationRange) = WrkBook.Worksheets(1).Cells(SourceRange).Value
也 - 出于兴趣 - 做所有的Excel文件有一个共同的命名约定?你如何存储这些文件名?阵列?常见的命名可能是最好的,就像 - MyFilei.xls是我是一个数字,你循环他们(For循环),并获得结果轮流 – Katana24 2013-05-01 13:58:37