我要做的是创建一个主文件,其中包含工作簿中所有文件的总数。但是,我还没有需要合计的文件。
这是一份费用报告,我的团队将填写他们的费用报告并将其保存在网络上的文件夹中。然后我希望能够运行一个宏,该宏总计文件夹中所有文件的范围(L15:L31)(G:\ Common \ 212 \ Expense Reports)。公式中将会有大量且不断增加的文件,因此我必须选择单个文件的任何内容都是不切实际的。
举个例子:
ExpenseReport1.xls的值为
L15 4
L16 5
L17 6
ExpenseReport2.xls的值为
L15 8
L16 1
L17 3
我希望我的Totals文件能够将这些文件合在一起并以
返回L15 12
L16 6
L17 9
答案 0 :(得分:0)
要获取文件夹路径,下面的宏提供了选择其中一个源文件的选项。然后,它会查看该文件夹中的每个费用报表,并将这些值添加到主电子表格中。
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