如何从路径提取文件名?

如何在 VBA 中从 C:\Documents\myfile.pdf中提取文件名 myfile.pdf

360491 次浏览

这是从 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

使用 Office2000/2003 VBA 中的文件和目录的最佳方法是使用脚本库。

创建一个文件系统对象并使用它执行所有操作。

早期装订:

添加对 Microsoft 脚本运行时(Tools > References in the IDE)的引用。

Dim fso as new FileSystemObject
Dim fileName As String
fileName = fso.GetFileName("c:\any path\file.txt")

后期绑定 (更多信息请参见注释)

With CreateObject("Scripting.FileSystemObject")
fileName = .GetFileName(FilePath)
extName = .GetExtensionName(FilePath)
baseName = .GetBaseName(FilePath)
parentName = .GetParentFolderName(FilePath)
End With

FileSystemObject很棒。它提供了很多特性,比如获取特殊文件夹(我的文档等)、以面向对象的方式创建、移动、复制、删除文件和目录。

Dir("C:\Documents\myfile.pdf")

将返回文件名,但仅当它存在时。

要获取 Excel 宏中的文件名,需要:

filname = Mid(spth, InStrRev(spth, "\", Len(spth)) + 1, Len(spth))
MsgBox Mid(filname, 1, InStr(filname, ".") - 1)

如果你想要一个更健壮的解决方案,既能提供完整文件夹的路径,又能提供文件名,这里是:

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

或者作为一个子函数:

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

传递带有文件完整路径的第一个参数,它将被设置为文件夹的路径,而第二个参数将被设置为文件名。

Dim sFilePath$, sFileName$
sFileName = Split(sFilePath, "\")(UBound(Split(sFilePath, "\")))

下面是一个没有代码的解决方案,VBA 可以在 Excel 公式栏中工作:

提取文件名:

=RIGHT(A1,LEN(A1)-FIND("~",SUBSTITUTE(A1,"\","~",LEN(A1)-LEN(SUBSTITUTE(A1,"\","")))))

要提取文件路径:

=MID(A1,1,LEN(A1)-LEN(MID(A1,FIND(CHAR(1),SUBSTITUTE(A1,"\",CHAR(1),LEN(A1)-LEN(SUBSTITUTE(A1,"\",""))))+1,LEN(A1))))

我需要的是路径,不是文件名。

因此,要提取代码中的文件路径:

JustPath = Left(sFileP, Len(sFileP) - Len(Split(sFileP, "\")(UBound(Split(sFileP, "\")))))

我已经阅读了所有的答案,我想补充一个我认为赢了,因为它的简单性。与公认的答案不同,这不需要递归。它也不需要引用 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/ 包含这段代码和其他函数,用于解析文件路径、扩展名,甚至不包含扩展名的文件名。

下面是我编写的一个简单的 VBA 解决方案,可以使用 Windows、 Unix、 Mac 和 URL 路径。

sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "\") + 1)


sFolderName = Left(sPath, Len(sPath) - Len(sFileName))

您可以使用以下代码测试输出:

'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

另见: Wikipedia-Path (计算)

这是从 Twiggy@http://archive.atomicmpc.com.au和其他地方收集到的:

'since the file name and path were used several times in code
'variables were made public


Public FName As Variant, Filename As String, Path As String


Sub xxx()
...
If Not GetFileName = 1 Then Exit Sub '
...
End Sub


Private Function GetFileName()
GetFileName = 0 'used for error handling at call point in case user cancels
FName = Application.GetOpenFilename("Ramp log file (*.txt), *.txt")
If Not VarType(FName) = vbBoolean Then GetFileName = 1 'to assure selection was made
Filename = Split(FName, "\")(UBound(Split(FName, "\"))) 'results in file name
Path = Left(FName, InStrRev(FName, "\")) 'results in path
End Function
Dim nme As String = My.Computer.FileSystem.GetFileInfo(pathFicheiro).Name
Dim dirc As String = My.Computer.FileSystem.GetFileInfo(nomeFicheiro).Directory

如果确定文件实际存在于磁盘上,最简单的方法是:

Dim fileName, filePath As String
filePath = "C:\Documents\myfile.pdf"
fileName = Dir(filePath)

如果您不确定是否存在文件,或者只想从给定的路径中提取文件名,那么最简单的方法是:

fileName = Mid(filePath, InStrRev(filePath, "\") + 1)

我不能相信这些答案有多么复杂... (无意冒犯!)

这里有一个 单行函数单行函数,它可以完成这项工作:


**Extract Filename from <code>x:\path\filename</code>:**

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

**Extract Path from <code>x:\path\filename</code>:**

Function getPath(pf)As String:getPath=Left(pf,InStrRev(pf,"\")):End Function

例子:

examples

Function file_name_only(file_path As String) As String


Dim temp As Variant


temp = Split(file_path, Application.PathSeparator)


file_name_only = temp(UBound(temp))


End Function
  1. 在这里你给你的文件名作为函数的输入
  2. VBA 的分割函数通过使用“”作为路径分隔符将路径分割成不同的部分,并将它们存储在一个名为“ temp”的数组中
  3. UBound ()查找数组的最大项目数,并最终将结果分配给“ file _ name _ only”函数

希望这对你有帮助。

我正在使用这个函数..。 功能:

Function FunctionGetFileName(FullPath As String) As String
'Update 20140210
Dim splitList As Variant
splitList = VBA.Split(FullPath, "\")
FunctionGetFileName = splitList(UBound(splitList, 1))
End Function

现在进去

=FunctionGetFileName(A1) in youe required cell.

或者你可以用这些..。

=MID(A1,FIND("*",SUBSTITUTE(A1,"\","*",LEN(A1)-LEN(SUBSTITUTE(A1,"\",""))))+1,LEN(A1))