我有一个excel文件,它使用VBA获取目录中的所有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
答案 0 :(得分:0)
如果您只是在查找文件名,可以使用工作簿对象的.Name属性,但它确实为您提供了文件扩展名。如果需要完整文件路径,可以使用工作簿对象的.Path属性。一旦你做了其中一个,你可以在获取它们时将值分配给单元格,或者将它们全部存储在一个数组中并一次性输出到列中。