Excel VBA:正则expression式 – 获取文件名

我如何得到文件名(没有path和扩展名)
像“MyFileName”
从以下完整path?
C:\ A_B \ CD \ E_ \ F0123456789□\ G \ MyFileName.txt

 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 

使用即时窗口

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

编辑 :另一种方法

 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 

InStrRev将查找string中最后一次出现的字符。 search\并在那里分割

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

现在要脱下延伸

 FileNameWithoutExt=left(FileName,instrrev(FileName,".")-1) 

如果这是您有权访问的真实文件,则可以使用Dir

 sFileOnly = Dir(sPathAndFile) 

如果它不是一个真正的文件或者你没有访问它,这将返回一个空string。

 Set regEx = New RegExp regEx.Pattern = ".*\\" regEx.IgnoreCase = True filename = regEx.Replace(fullpath, "") 
  Sub Test() Dim fileNameOnly As String fileNameOnly = Left$(Split("C:\A_B\CD\E_\F0123456789\G\MyFileName.txt", "\")(UBound(Split("C:\A_B\CD\E_\F0123456789\G\MyFileName.txt", "\"))), InStrRev(Split("C:\A_B\CD\E_\F0123456789\G\MyFileName.txt", "\")(UBound(Split("C:\A_B\CD\E_\F0123456789\G\MyFileName.txt", "\"))), ".") - 1) Debug.Print Strtf End Sub