2

我想编写一个宏来打开 30 个结构相同的 excel 文件。

宏应该对所有文件进行操作,并从每个文件中获取结果并将其放入另一个 excel 文件中。这意味着:所有结果(值)将被复制到目标文件中。

  1. 如何编写 VBA 代码来打开多个文件?

  2. 如何从每个文件中获取结果并将它们放入我的destination.xls 文件中?

4

2 回答 2

2

尝试检查FileSearch.LookIn 属性
,将该示例修改为类似的内容。(这需要你所有的 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
于 2013-05-01T13:51:10.337 回答
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
于 2020-05-22T01:03:37.697 回答