我想写一个宏,它将打开30个excel文件,它们都具有相同的结构。
宏应对所有文件执行操作,并从每个文件中获取结果并将其放入另一个excel文件中。这意味着:所有结果(值)将被复制到目标文件中。
如何编写VBA代码以打开多个文件?
如何从每个文件中获取结果并将它们放在我的destination.xls文件中?
答案 0 :(得分:2)
尝试查看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
答案 1 :(得分:0)
我认为您正在寻求解决方案,要求用户选择要打开和处理的文件?
尝试一下...
Option Explicit
Sub opening_multiple_file()
Dim i As Integer
'Opening File dialog box
With Application.FileDialog(msoFileDialogFilePicker)
'Enabling multiple files select
.AllowMultiSelect = True
.Filters.Clear
'Only Excel files can be selected
.Filters.Add "Excel Files", "*.xls*"
If .Show = True Then
For i = 1 To .SelectedItems.Count
'Opening selected file
Workbooks.Open .SelectedItems(i)
'etc do other things with it
Next i
End If
End With
End Sub