Excel VBA: Regular Expression - get file name

后端 未结 5 1710
轮回少年
轮回少年 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: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
    

提交回复
热议问题