vba 如何在VBA中获取excel文件名/路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1895616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the excel file name / path in VBA
提问by Veera
Say, I'm writing a VBA inside my excel file sample.xls. Now I want to get the full pathof sample.xlsin my VBA. How do I do it?
说,我正在我的 excel 文件sample.xls 中编写一个 VBA 。现在我想的全路径的sample.xls在我的VBA。我该怎么做?
回答by Fionnuala
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.FullNamecould 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, ActiveWorkbookcould be the correct choice, if it is guaranteed to be active at execution time.)
(根据评论进行更新:ActiveWorkbook.FullName如果其他办公文件可能已打开(编辑)并处于活动状态,则前者使用的更有可能是错误的。但如果您将宏存储在另一个文件中,如用户@user7296559此处所述,以及真的想要宏使用文件的文件名ActiveWorkbook,如果它保证在执行时处于活动状态,则可能是正确的选择。)
回答by APW
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))
回答by Mitch Wheat
strScriptFullname = WScript.ScriptFullName
strScriptPath = Left(strScriptFullname, InStrRev(strScriptFullname,"\"))
回答by Louis
If you need path only this is the most straightforward way:
如果您只需要路径,这是最直接的方法:
PathOnly = ThisWorkbook.Path
回答by user7296559
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 是一个要使用的文件,因为它处理两种情况。
回答by Riccardo La Marca
There is a universal way to get this:
有一种通用的方法可以得到这个:
Function FileName() As String
FileName = Mid(Application.Caption, 1, InStrRev(Application.Caption, "-") - 2)
End Function

