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
Set regEx = New RegExp
regEx.Pattern = ".*\\"
regEx.IgnoreCase = True
filename = regEx.Replace(fullpath, "")
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.
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)
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
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