我如何获得文件名(没有路径和扩展名)
像“我的文件名”
从以下完整路径?
C:\A_B\C.D\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\C.D\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
关于Excel VBA : Regular Expression - get file name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12354592/