如何从路径中提取文件名?

时间:2009-11-16 16:39:21

标签: string vba

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

15 个答案:

答案 0 :(得分:116)

在VBA for Office 2000/2003中使用文件和目录的最佳方法是使用脚本库。添加对Microsoft Scripting Runtime的引用(IDE中的工具>引用)。

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

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

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

答案 1 :(得分:45)

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

将返回文件名,但仅在文件名存在时才会返回。

答案 2 :(得分:38)

这取自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

答案 3 :(得分:26)

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

答案 4 :(得分:9)

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

答案 5 :(得分:5)

我无法相信这些答案中有些过于复杂......(没有冒犯!)

这是单行功能,可以完成工作:

**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

答案 6 :(得分:4)

如果您想要一个更强大的解决方案,它将为您提供完整文件夹的路径和文件名,这里是:

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

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

答案 7 :(得分:4)

这是我编写的一个简单的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 (computing)

答案 8 :(得分:3)

要在excel宏中获取文件名,请执行以下操作:

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

答案 9 :(得分:3)

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

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

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

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

答案 10 :(得分:1)

这是一个没有代码的替代解决方案。此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))))

答案 11 :(得分:0)

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

所以要在代码中提取文件路径:

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

答案 12 :(得分:0)

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

答案 13 :(得分:0)

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的split函数通过使用“ \”作为路径分隔符将路径分成不同的部分,并将它们存储在名为“ temp”的数组中。
  3. UBound()找到数组的最大项数,最后将结果分配给“ file_name_only”函数

希望这会有所帮助。

答案 14 :(得分:0)

我正在使用此功能... VBA功能:

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))