使用VBA从多个工作表中总结多个工作簿,而无需手动select

我一直在试图将多个工作簿与多个工作表相同的格式。 到目前为止,我正在关注这个post 。 虽然我看了这个 ,而且这个链接想要一个好的和短的想法,第一个工作很好,所以我跟着。

到目前为止,我首先提到的这个post已经相当不错了。 但是,有一个(小)问题我无法在任何地方得到答案。 我怎样才能使代码工作,而不必select文件? 我已经把它们全部列在名为“Main”的工作簿中,而且它们都在同一个文件夹中,但是,我不知道如何自动获取它们,而无需手动select。

例如,我想在工作簿“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 

如果您将完整的文件path存储在某个范围内,为什么不循环遍历该范围并打开每个文件?

 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 

如果您的模板范围具有工作簿名称,但没有完整的文件path,则必须执行一些额外的工作并获取主工作簿的目录(假定所有其他文件都在同一目录中),然后追加该工作簿的名称。