获取脚本中声明的“文件名”

时间:2018-08-17 03:25:49

标签: excel excel-vba

基本上,每次我获取一张新工作表时,我都希望同时获取文件名并将其放置在单元格B2中。

但是,我无法调用文件名将其放置在任何单元格中。

Sub GetSheets()
    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)
        Next Sheet
        Workbooks(Filename).Close
        Filename = Dir()
        Call runDel
    Loop
End Sub

2 个答案:

答案 0 :(得分:0)

如果其余代码当前正在运行,则紧接在以下位置:

Sheet.Copy After:=ThisWorkbook.Sheets(1)

您应该可以添加:

ThisWorkbook.Sheets(2).Range("B2").Value = Filename

赞:

Sub GetSheets()

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)
            ThisWorkbook.Sheets(2).Range("B2").Value = Filename
        Next Sheet
    Workbooks(Filename).Close
    Filename = Dir()
    Call runDel
Loop

End Sub

答案 1 :(得分:0)

如果您想弄清楚如何引用新创建的图纸上的单元格,或者它只是文件名而没有要检索的路径,那么以下方法应该可以工作。

使用Dir(Path&“ * .xls”)设置Filename变量后,可以使用[Right]和[InstrRev]函数的组合提取文件名,如下所示:

Range(“ B2”)= Right(文件名,Len(文件名)-InstrRev(文件名,“ \”))

要引用新创建的工作表上的单元格,由于您是在Sheet(1)之后插入工作表,因此索引将为2。可以通过以下方式引用它: ThisWorkbook.Sheets(2).Range(“ B2)=文件名

如:

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) Next Sheet ThisWorkbook.Sheets(2).Range("B2") = Right(Filename, Len(Filename) - InStrRev(Filename, "\")) Workbooks(Filename).Close Filename = Dir() Call runDel Loop End Sub

0