我如何获得文件名(没有路径和扩展名)
喜欢" MyFileName"
从以下完整路径?
C:\ A_B \ C.D \ E_ \ F0123456789 \ G变\ MyFileName.txt
答案 0 :(得分:2)
InStrRev
会在字符串中找到最后一个字符。搜索\
并将其拆分
FullFileName="C:\A_B\C.D\E_\F0123456789\G\MyFileName.txt"
FileName=mid(FullFileName,instrrev(FullFileName,"\")+1)
现在取消扩展
FileNameWithoutExt=left(FileName,instrrev(FileName,".")-1)
答案 1 :(得分:2)
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
答案 2 :(得分:1)
如果它是您可以访问的真实文件,则可以使用Dir
sFileOnly = Dir(sPathAndFile)
如果它不是真实文件或您无法访问它,则会返回一个空字符串。
答案 3 :(得分:0)
Set regEx = New RegExp
regEx.Pattern = ".*\\"
regEx.IgnoreCase = True
filename = regEx.Replace(fullpath, "")
答案 4 :(得分:0)
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