我要在导入excel工作簿后获取工作表名称。 在下面,我能够获取文件名,现在我想从导入的excel文件中获取工作表名称,并将其放置在单元格“ C2”中
Sub GetSheets()
'Update Excel Junction.com
Path = "C:\Users\momo\Desktop\Miscellaneous Shipment Packing List\New folder\"
Filename = Dir(Path & "*.xls")
Do While Filename <> ""
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Range("B2").Value = Filename
Next Sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub
答案 0 :(得分:0)
只需在循环中添加两行,即可添加工作表名称:
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
k = 1
For Each Sheet In ActiveWorkbook.Sheets
Cells(2, 2+k).Value = Sheet.Name
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Range("B2").Value = Filename
k = k + 1
Next Sheet
在此示例中,如果您的工作簿有几张工作表,则这些工作表将添加到单元格C D E F等中...
答案 1 :(得分:0)
尝试
option explicit
Sub GetSheets()
dim wb1 as workbook, sh as worksheet
dim filename as string, path as string
set wb1 = thisworkbook
Path = "C:\Users\momo\Desktop\Miscellaneous Shipment Packing List\New folder\"
Filename = Dir(Path & "*.xls")
Do While Filename <> ""
with Workbooks.Open( Filename:=Path & Filename, ReadOnly:=True)
For Each sh In .workSheets
sh.Copy After:=wb1.workSheets(1)
wb1.worksheets(1).cells(rows.count, "B").end(xlup).offset(1,0) = Filename
wb1.worksheets(1).cells(rows.count, "B").end(xlup).offset(0,1) = sh.name
Next sh
.Close savechanges:=false
end with
Filename = Dir()
Loop
End Sub
rows.count不需要父级,因为wb1是xls或xlsx,并且您正在打开xls(除非您打开的工作簿超过65K)。