我一直在尝试将多个工作簿与具有相同格式的多个工作表相加。到目前为止,我正在关注post。虽然我已经看了this和this链接试图获得一个好的和简短的想法,但第一个工作得很好,所以我跟着。
到目前为止,我首先提到的帖子相当顺利。但是,有一个(小)问题,我无法在任何地方得到答案。如何在不必选择文件的情况下使代码工作?我把它们都列在工作簿中名为“Main”的列中,它们都在同一个文件夹中,但是,我不知道如何自动获取它们,而不必手动选择。
例如,我想在工作簿“Main”中的文件(及其地址)名称中,例如,Sheet(1),Range(“A1:A100”)。
任何人都可以帮我一把吗?这是我正在使用的代码:
Sub Results()
Dim WS_Count As Integer 'not being used
Dim FileNameXls, f
Dim wb As Workbook, i As Integer
'locate where are the Templates and how many sheets they have
Range("Template").Select
ncol = ActiveCell.Column
Selection.End(xlToRight).Select
lastcolumn = ActiveCell.Column
numSheets = lastcolumn - ncol
'Name of the First Template
Business = Cells(2, ncol)
Windows("StressTestPlatform.xlsm").Activate
'THIS IS WHERE I'M ASKED TO SELECT THE FILES
FileNameXls = Application.GetOpenFilename(filefilter:="Excel Files, *.xl*", MultiSelect:=True)
If Not IsArray(FileNameXls) Then Exit Sub
Application.ScreenUpdating = False
For Each f In FileNameXls
Set wb = Workbooks.Open(f)
For i = 3 To numSheets
wb.Worksheets(i).Range("C5:H93").Copy
'The Range must be changed accordingly to the template being used
Workbooks("Main.xlsm").Sheets("Results").Range("C5:H93").PasteSpecial Paste:=xlPasteValues, Operation:=xlAdd, SkipBlanks:=True, Transpose:=False
Next i
Application.CutCopyMode = False
wb.Close SaveChanges:=False
Next f
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:1)
如果你有一个存储在某个范围内的完整文件路径,为什么不循环遍历该范围并打开每个文件?
Dim TemplateRange as Range
Dim r as Range
Set TemplateRange = ThisWorkbook.Sheets(1).Range("A1:A100")
'^^ Change this to wherever your list of files is stored.
'You can eliminate the GetOpenFilename dialog entirely
'FileNameXls = Application.GetOpenFilename(filefilter:="Excel Files, *.xl*", MultiSelect:=True)
'Instead, just loop through the template range one by one and get
'each filename and proceed with the rest of your code as before
For Each r In TemplateRange
FileNameXls = r.Value2
Set wb = Workbooks.Open(FileNameXls)
'
'The rest of your code as before
'
Next r
如果模板范围包含工作簿名称,而不是完整文件路径,则必须执行一些额外工作并获取主工作簿的目录(假设所有其他文件位于同一目录中),然后将工作簿名称附加到该。