将组合的excel文件数据的文件名追加到主表中

我有一个使用VBA来获取目录中的所有excel文件(所有文件具有相同的结构/标题)的excel文件,并将它们全部组合到从B列开始的新的excel文件中。

在这里输入图像说明

我无法弄清楚如何在打开每个文件时获取文件的名称,并将该名称放在A列中,每一行都附加了数据。 请帮忙。

Dim bookList As Workbook Dim path As String Dim mergeObj As Object, dirObj As Object, filesObj As Object, everyObj As Object Dim rowCount As String Dim myRange As String Application.ScreenUpdating = False Set mergeObj = CreateObject("Scripting.FileSystemObject") 'change folder path of excel files here path = InputBox("Enter the path to the folder containing the excel files you want to combine.", "Excel Combiner") Set dirObj = mergeObj.Getfolder(path) Set filesObj = dirObj.Files For Each everyObj In filesObj Set bookList = Workbooks.Open(everyObj) 'Grab filename from each open file Dim MyName As String MyName = everyObj.Name 'change "A2" with cell reference of start point for every files here 'for example "B3:IV" to merge all files start from columns B and rows 3 'If you're files using more than IV column, change it to the latest column 'Also change "A" column on "A65536" to the same column as start point Range("A2:IV" & Range("A65536").End(xlUp).Row).Copy ThisWorkbook.Worksheets(2).Activate 'Do not change the following column. It's not the same column as above Range("A65536").End(xlUp).Offset(1, 1).PasteSpecial Application.CutCopyMode = False 'Paste scan name into Column A NEED SOMETHING HERE 

如果您只是在查找文件名,您可以使用工作簿对象的.Name属性,但是它也会为您提供文件扩展名。 如果您想要完整的文件path,则可以使用工作簿对象的.Path属性。 一旦你做了其中的一个,你可以将值赋给单元格,或者将它们全部存储在一个数组中,并一次输出到列中。