简体   繁体   中英

Get filepath of another opened workbook by VBA

I have written a VBA script which collects data from another open file selected by user. Getting data out of the Excel file isn't a problem, but now I want to create a new file in the same folder as the file where the data is from.

I can't get the path of the data file. How can I do this?

Normally I would do Application.ThisWorkbook.Path , I thought for another file I could use Application.Workbooks(objWB).Path but that doesn't work.

If you are in the users file you could set objWB as the ActiveWorkbook and then create a new file from there

Sub SaveToActiveFolder()

Dim objWB As Workbook
Set objWB = ActiveWorkbook
Dim NewWB As Workbook
Set NewWB = Workbooks.Add

    With NewWB
        .SaveAs Filename:=objWB.Path & "\NewFile1.xlsm"_
, FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
    End With

End Sub

The file NewFile1.xlsm will then be created and saved in the same location as the first file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM