Excel VBA: Regular Expression - get file name

后端 未结 5 1584
轮回少年
轮回少年 2021-01-25 07:30

How do I get just filename (without path and extension)
like \"MyFileName\"
from the following full path?
C:\\A_B\\C.D\\E_\\F0123456789\\G\\MyFileName.txt

相关标签:
5条回答
  • 2021-01-25 07:51
    Set regEx = New RegExp
    regEx.Pattern = ".*\\"
    regEx.IgnoreCase = True
    filename = regEx.Replace(fullpath, "")
    
    0 讨论(0)
  • 2021-01-25 07:53

    If it's a real file that you have access to, you can use Dir

    sFileOnly = Dir(sPathAndFile)
    

    If it's not a real file or you don't have access to it, this will return an empty string.

    0 讨论(0)
  • 2021-01-25 07:55

    InStrRev will find the last occurrence of a character in a string. Search for \ and split it there

    FullFileName="C:\A_B\C.D\E_\F0123456789\G\MyFileName.txt"
    FileName=mid(FullFileName,instrrev(FullFileName,"\")+1)
    

    now to take off the extension

    FileNameWithoutExt=left(FileName,instrrev(FileName,".")-1)
    
    0 讨论(0)
  • 2021-01-25 07:56
    Public Function GetFileNameWithoutExt(ByVal fullPath As String) As String
    Dim fileName As String
    Dim fileNameWithoutExt As String
    
    Dim lastSlash As Integer
    Dim positionOfDot As Integer
    
    lastSlash = InStrRev(fullPath, "\")
    fileName = Mid(fullPath, lastSlash + 1)
    
    positionOfDot = InStr(1, fileName, ".")
    fileNameWithoutExt = Mid(fileName, 1, positionOfDot - 1)
    
    GetFileNameWithoutExt = fileNameWithoutExt
    End Function
    

    Using the immediate window

    ?GetFileNameWithoutExt("C:\A_B\C.D\E_\F0123456789\G\MyFileName.txt")
    

    EDIT: Another method

    Public Function GetFileNameWithoutExt2(ByVal fullPath As String) As String
    Dim fileName As String
    Dim splittedData
    Dim fileNameWithoutExt As String
    
    splittedData = Split(fullPath, "\")
    fileName = splittedData(UBound(splittedData))
    
    fileNameWithoutExt = Split(fileName, ".")(0)
    
    GetFileNameWithoutExt2 = fileNameWithoutExt
    End Function
    
    0 讨论(0)
  • 2021-01-25 08:02
        Sub Test()
            Dim fileNameOnly As String
            fileNameOnly = Left$(Split("C:\A_B\C.D\E_\F0123456789\G\MyFileName.txt", "\")(UBound(Split("C:\A_B\C.D\E_\F0123456789\G\MyFileName.txt", "\"))), InStrRev(Split("C:\A_B\C.D\E_\F0123456789\G\MyFileName.txt", "\")(UBound(Split("C:\A_B\C.D\E_\F0123456789\G\MyFileName.txt", "\"))), ".") - 1)
            Debug.Print Strtf    
        End Sub
    
    0 讨论(0)
提交回复
热议问题