简体   繁体   English

如何在 VBA 中获取 excel 文件名/路径

[英]How to get the excel file name / path in VBA

Say, I'm writing a VBA inside my excel file sample.xls .说,我正在我的 excel 文件sample.xls 中编写一个 VBA。 Now I want to get the full path of sample.xls in my VBA.现在我想在我的 VBA 中获取sample.xls完整路径 How do I do it?我该怎么做?

If you mean VBA, then you can use FullName, for example:如果您的意思是 VBA,那么您可以使用 FullName,例如:

strFileFullName = ThisWorkbook.FullName

(updated as considered by the comments: the former used ActiveWorkbook.FullName could more likely be wrong, if other office files may be open(ed) and active. But in case you stored the macro in another file, as mentioned by user @user7296559 here , and really want the file name of the macro-using file, ActiveWorkbook could be the correct choice, if it is guaranteed to be active at execution time.) (根据评论更新:如果其他办公文件可能已打开(编辑)并处于活动状态,则前者使用的ActiveWorkbook.FullName可能更可能是错误的。但如果您将宏存储在另一个文件中,如用户 @user7296559 所述在这里,如果真的想要宏使用文件的文件名, ActiveWorkbook可能是正确的选择,如果它保证在执行时处于活动状态。)

this is a simple alternative that gives all responses, Fullname, Path, filename.这是一个简单的替代方案,它提供所有响应、全名、路径、文件名。

Dim FilePath, FileOnly, PathOnly As String

FilePath = ThisWorkbook.FullName
FileOnly = ThisWorkbook.Name
PathOnly = Left(FilePath, Len(FilePath) - Len(FileOnly))
   strScriptFullname = WScript.ScriptFullName 
   strScriptPath = Left(strScriptFullname, InStrRev(strScriptFullname,"\")) 

如果您只需要路径,这是最直接的方法:

PathOnly = ThisWorkbook.Path

ActiveWorkbook.FullName would be better I think, in case you have the VBA Macro stored in another Excel Workbook, but you want to get the details of the Excel you are editing, not where the Macro resides.我认为 ActiveWorkbook.FullName 会更好,以防您将 VBA 宏存储在另一个 Excel 工作簿中,但您想获取正在编辑的 Excel 的详细信息,而不是宏所在的位置。

If they reside in the same file, then it does not matter, but if they are in different files, and you want the file where the Data is rather than where the Macro is, then ActiveWorkbook is the one to go for, because it deals with both scenarios.如果它们驻留在同一个文件中,那么没关系,但是如果它们在不同的文件中,并且您想要数据所在的文件而不是宏所在的文件,那么 ActiveWorkbook 就是要使用的文件,因为它处理两种情况。

if you need path only without file name:如果您只需要没有文件名的路径:

ActiveWorkbook.Path

it would return D:\\Folder它会返回 D:\\Folder

if you need file path with file name also:如果您还需要带有文件名的文件路径:

ActiveWorkbook.FullName

it would return D:\\Folder\\sample.xls它会返回 D:\\Folder\\sample.xls

if you need file name only:如果您只需要文件名:

ActiveWorkbook.Name

it would return sample.xls它会返回 sample.xls

so if you want combine file path and file name to get full directory don't forget to add "" between.所以如果你想结合文件路径和文件名来获得完整的目录,不要忘记在它们之间添加“”。 otherwise its simpler using .Path否则使用 .Path 更简单

There is a universal way to get this:有一种通用的方法可以做到这一点:

Function FileName() As String
    FileName = Mid(Application.Caption, 1, InStrRev(Application.Caption, "-") - 2)
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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