代码之家  ›  专栏  ›  技术社区  ›  Johan

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

  •  48
  • Johan  · 技术社区  · 16 年前

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

    15 回复  |  直到 8 年前
        1
  •  45
  •   Gonzalo    16 年前

    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
    
        2
  •  143
  •   ZygD    5 年前

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

    早期绑定:

    添加对Microsoft脚本运行时的引用(工具>IDE中的引用)。

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

    Late binding (详见评论)

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

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

        3
  •  49
  •   Dick Kusleika    12 年前
    Dir("C:\Documents\myfile.pdf")
    

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

        4
  •  39
  •   user2780436    12 年前

    我已经通读了所有的答案,我想再添加一个我认为因为简单而胜出的答案。与公认的答案不同,这不需要递归。它也不需要引用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/ 具有此代码和其他函数,用于解析文件路径、扩展名,甚至不带扩展名的文件名。

        5
  •  10
  •   Jon Egerton Aditya kumar sahoo    13 年前
    Dim sFilePath$, sFileName$
    sFileName = Split(sFilePath, "\")(UBound(Split(sFilePath, "\")))
    
        6
  •  10
  •   ashleedawg    8 年前

    我真不敢相信这些答案有多么复杂(没有冒犯!)

    这里有一个 这将完成工作:


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

        7
  •  5
  •   dan    13 年前

    如果您想要一个更健壮的解决方案,该解决方案将为您提供完整文件夹的路径和文件名,请参阅:

    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
    

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

        8
  •  5
  •   Yogi    12 年前

    下面是我编写的一个简单的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)

        9
  •  4
  •   Florent Joice    13 年前

    filname = Mid(spth, InStrRev(spth, "\", Len(spth)) + 1, Len(spth))
    MsgBox Mid(filname, 1, InStr(filname, ".") - 1)
    
        10
  •  4
  •   ePandit    9 年前

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

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

    fileName = Mid(filePath, InStrRev(filePath, "\") + 1)
    
        11
  •  1
  •   live-love    12 年前

    要提取文件名,请执行以下操作:

    =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))))
    
        12
  •  1
  •   mishu36    7 年前
    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. VBA的拆分功能使用“\”作为路径分隔符,将路径拆分为不同的部分;将它们存储在名为“temp”的数组中
    2. UBound()查找数组的最大项数,最后将结果分配给“file\u name\u only”函数

    希望这会有帮助。

        13
  •  1
  •   Zoe - Save the data dump 张群峰    6 年前

    我正在使用这个函数。。。 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))
    
        14
  •  0
  •   Darwind    12 年前

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

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

    JustPath = Left(sFileP, Len(sFileP) - Len(Split(sFileP, "\")(UBound(Split(sFileP, "\"))))) 
    
        15
  •  0
  •   Dan    11 年前

    这是从小树枝上捡来的@ 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
    
        16
  •  -1
  •   Paulos02    10 年前
    Dim nme As String = My.Computer.FileSystem.GetFileInfo(pathFicheiro).Name
    Dim dirc As String = My.Computer.FileSystem.GetFileInfo(nomeFicheiro).Directory