vba 如何从路径中提取文件名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1743328/
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 extract file name from path?
提问by Johan
How do I extract the filename myfile.pdffrom C:\Documents\myfile.pdfin VBA?
如何myfile.pdf从C:\Documents\myfile.pdfVBA 中提取文件名?
采纳答案by Gonzalo
This is taken from snippets.dzone.com:
Function GetFilenameFromPath(ByVal strPath As String) As String
' Returns the rightmost characters of a string upto but not including the rightmost '\'
' e.g. 'c:\winnt\win.ini' returns 'win.ini'
If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
End If
End Function
回答by Zen
The best way of working with files and directories in VBA for Office 2000/2003 is using the scripting library. Add a reference to Microsoft Scripting Runtime (Tools > References in the IDE).
在 VBA for Office 2000/2003 中处理文件和目录的最佳方式是使用脚本库。添加对 Microsoft Scripting Runtime 的引用(IDE 中的“工具”>“引用”)。
Create a filesystem object and do all operations using that.
创建一个文件系统对象并使用它执行所有操作。
Dim fso as new FileSystemObject
Dim fileName As String
fileName = fso.GetFileName("c:\any path\file.txt")
The FileSystemObject is great. It offers a lot of features such as getting special folders (My documents, etc), creating, moving, copying, deleting files and directories in an object oriented manner. Check it out.
FileSystemObject 很棒。它提供了许多功能,例如以面向对象的方式获取特殊文件夹(我的文档等)、创建、移动、复制、删除文件和目录。一探究竟。
回答by Dick Kusleika
Dir("C:\Documents\myfile.pdf")
will return the file name, but only if it exists.
将返回文件名,但前提是它存在。
回答by user2780436
I've read through all the answers and I'd like to add one more that I think wins out because of its simplicity. Unlike the accepted answer this does not require recursion. It also does not require referencing a FileSystemObject.
我已经通读了所有答案,我想再添加一个我认为因其简单性而胜出的答案。与接受的答案不同,这不需要递归。它还不需要引用 FileSystemObject。
Function FileNameFromPath(strFullPath As String) As String
FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, "\"))
End Function
http://vba-tutorial.com/parsing-a-file-string-into-path-filename-and-extension/has this code plus other functions for parsing out the file path, extension and even the filename without the extension.
http://vba-tutorial.com/parsing-a-file-string-into-path-filename-and-extension/具有此代码以及其他用于解析文件路径、扩展名甚至没有扩展名的文件名的函数。
回答by ashleedawg
I can't believe how overcomplicated some of these answers are... (no offence!)
我无法相信其中一些答案是多么的复杂......(无意冒犯!)
Here's a single-line functionthat will get the job done:
这是一个可以完成工作的单行函数:


Function getFName(pf)As String:getFName=Mid(pf,InStrRev(pf,"\")+1):End Function


Function getPath(pf)As String:getPath=Left(pf,InStrRev(pf,"\")):End Function
Examples:
例子:
回答by Artur Piwkowski
Dim sFilePath$, sFileName$
sFileName = Split(sFilePath, "\")(UBound(Split(sFilePath, "\")))
回答by dan
If you want a more robust solution that will give you both the full folder's path AND the filename, here it is:
如果您想要一个更强大的解决方案,该解决方案将为您提供完整文件夹的路径和文件名,这里是:
Dim strFileName As String, strFolderPath As String
Dim lngIndex As Long
Dim strPath() As String
strPath() = Split(OpenArgs, "\") 'Put the Parts of our path into an array
lngIndex = UBound(strPath)
strFileName = strPath(lngIndex) 'Get the File Name from our array
strPath(lngIndex) = "" 'Remove the File Name from our array
strFolderPath = Join(strPath, "\") 'Rebuild our path from our array
Or as a sub/function:
或作为子/功能:
Private Sub SeparatePathAndFile(ByRef io_strFolderPath As String, ByRef o_strFileName As String)
Dim strPath() As String
Dim lngIndex As Long
strPath() = Split(io_strFolderPath, "\") 'Put the Parts of our path into an array
lngIndex = UBound(strPath)
o_strFileName = strPath(lngIndex) 'Get the File Name from our array
strPath(lngIndex) = "" 'Remove the File Name from our array
io_strFolderPath = Join(strPath, "\") 'Rebuild our path from our array
End Sub
You pass the first parameter with the full path of the file and it will be set to the folder's path while the second parameter will be set to the file's name.
您使用文件的完整路径传递第一个参数,它将被设置为文件夹的路径,而第二个参数将被设置为文件的名称。
回答by ePandit
The simplest approach if you are sure the file physically exists on the disk:
如果您确定文件物理存在于磁盘上,最简单的方法是:
Dim fileName, filePath As String
filePath = "C:\Documents\myfile.pdf"
fileName = Dir(filePath)
If you are not sure about existence of file or just want to extract filename from a given path then, simplest approach is:
如果您不确定文件是否存在或只想从给定路径中提取文件名,那么最简单的方法是:
fileName = Mid(filePath, InStrRev(filePath, "\") + 1)
回答by Roberto
Here's a simple VBA solution I wrote that works with Windows, Unix, Mac, and URL paths.
这是我编写的一个简单的 VBA 解决方案,它适用于 Windows、Unix、Mac 和 URL 路径。
sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "\") + 1)
sFolderName = Left(sPath, Len(sPath) - Len(sFileName))
You can test the output using this code:
您可以使用以下代码测试输出:
'Visual Basic for Applications
http = "https://www.server.com/docs/Letter.txt"
unix = "/home/user/docs/Letter.txt"
dos = "C:\user\docs\Letter.txt"
win = "\Server01\user\docs\Letter.txt"
blank = ""
sPath = unix
sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "\") + 1)
sFolderName = Left(sPath, Len(sPath) - Len(sFileName))
Debug.print "Folder: " & sFolderName & " File: " & sFileName
Also see: Wikipedia - Path (computing)
另请参阅:维基百科 - 路径(计算)
回答by niki
To get the file name in an excel macro is:
在 excel 宏中获取文件名是:
filname = Mid(spth, InStrRev(spth, "\", Len(spth)) + 1, Len(spth))
MsgBox Mid(filname, 1, InStr(filname, ".") - 1)

