文件中多个工作簿中单元格的总范围
我想要做的是创build一个工作簿中的所有文件的总计主文件。 不过,我还没有需要汇总的文件。
这是一个费用报告,我的团队将填写他们的费用报告,并保存在networking上的文件夹。 然后,我希望能够运行总计文件夹(G:\ Common \ 212 \ Expense Reports)中所有文件的范围(L15:L31)的macros。 公式中将会有大量不断增长的文件,所以我不得不select单个文件的任何内容都是不切实际的。
举个例子:
ExpenseReport1.xls具有值
L15 4 L16 5 L17 6
ExpenseReport2.xls具有值
L15 8 L16 1 L17 3
我希望我的汇总文件将这些汇总在一起,然后再回来
L15 12 L16 6 L17 9
要获取文件夹path,下面的macros提供了select其中一个源文件的选项。 然后查看该文件夹中的每个费用报告并将这些值添加到主电子表格中。
Assumtions:
– 所有源文件都是.xls文件,其名称以“ExpenseReport”开头
– 每个工作簿中只有一张纸(如果不是这样,只需要添加工作表)
Sub imptrn() Application.DisplayAlerts = False Application.ScreenUpdating = False Dim myFile As String, pth As String, listResult As Variant, mastBook As Workbook, i As Integer, j As Integer Set mastBook = ThisWorkbook ChDrive mastBook.path ChDir mastBook.path myFile = Application.GetOpenFilename("Expense Reports (*.xls),*.xls") If myFile = "False" Then Exit Sub Workbooks.Open myFile pth = ActiveWorkbook.path & "\ExpenseReport*.xls" ActiveWorkbook.Close savechanges:=False listResult = fileList(pth) Select Case IsArray(listResult) Case True mastBook.Sheets(1).Range("L5:L17").ClearContents For i = LBound(listResult) To UBound(listResult) Workbooks.Open fileName:=listResult(i) For j = 15 To 17 mastBook.Sheets(1).Range("L" & j) = mastBook.Sheets(1).Range("L" & j) + Range("L" & j) Next j ActiveWorkbook.Close savechanges:=False If i = UBound(listResult) Then MsgBox "Totals updated." Next i Case False MsgBox "No matching files" End Select Application.ScreenUpdating = True Application.DisplayAlerts = True End Sub Function fileList(filePath As String) As Variant 'returns an array of fileNames, or False if no matching file found Dim fileArray() As Variant, fileCount As Integer, fileName As String On Error GoTo NoFilesFound fileCount = 0 fileName = Dir(filePath) If fileName = "" Then GoTo NoFilesFound Do While fileName <> "" fileCount = fileCount + 1 ReDim Preserve fileArray(1 To fileCount) fileArray(fileCount) = fileName fileName = Dir() Loop fileList = fileArray Exit Function NoFilesFound: fileList = False End Function