Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract filename from path [duplicate]

Tags:

wildcard

vba

I need to extract the filename from a path (a string):

e.g., "C:\folder\folder\folder\file.txt" = "file" (or even "file.txt" to get me started)

Essentially everything before and including the last \

I've heard of using wildcards in place of Regex (as it's an odd implementation in VBA?) but can't find anything solid.

Cheers in advance.

like image 370
Matt Rowles Avatar asked May 09 '11 05:05

Matt Rowles


5 Answers

I used kaveman's suggestion successfully as well to get the Full File name but sometimes when i have lots of Dots in my Full File Name, I used the following to get rid of the .txt bit:

FileName = Left(FullFileName, (InStrRev(FullFileName, ".") - 1))
like image 83
Alan Elston Avatar answered Oct 12 '22 03:10

Alan Elston


`You can also try:

Sub filen() Dim parts() As String Dim Inputfolder As String, a As String 'Takes input as any file on disk Inputfolder = Application.GetOpenFilename("Folder, *") parts = Split(Inputfolder, "\") a = parts(UBound(parts())) MsgBox ("File is: " & a) End Sub

This sub can display Folder name of any file

like image 24
Akash Avatar answered Oct 12 '22 01:10

Akash


I believe this works, using VBA:

Dim strPath As String
strPath = "C:\folder\folder\folder\file.txt"

Dim strFile As String
strFile = Right(strPath, Len(strPath) - InStrRev(strPath, "\"))

InStrRev looks for the first instance of "\" from the end, and returns the position. Right makes a substring starting from the right of given length, so you calculate the needed length using Len - InStrRev

like image 25
kaveman Avatar answered Oct 16 '22 01:10

kaveman


Thanks to kaveman for the help. Here is the full code I used to remove both the path and the extension (it is not full proof, does not take into consideration files that contain more than 2 decimals eg. *.tar.gz)

sFullPath = "C:\dir\dir\dir\file.txt"   
sFullFilename = Right(sFullPath, Len(sFullPath) - InStrRev(sFullPath, "\"))
sFilename = Left(sFullFilename, (InStr(sFullFilename, ".") - 1))

sFilename = "file"

like image 6
Matt Rowles Avatar answered Oct 16 '22 02:10

Matt Rowles


I was looking for a solution without code. This VBA works in the Excel Formula Bar:

To extract the file name:

=RIGHT(A1,LEN(A1)-FIND("~",SUBSTITUTE(A1,"\","~",LEN(A1)-LEN(SUBSTITUTE(A1,"\","")))))

To extract the file path:

=MID(A1,1,LEN(A1)-LEN(MID(A1,FIND(CHAR(1),SUBSTITUTE(A1,"\",CHAR(1),LEN(A1)-LEN(SUBSTITUTE(A1,"\",""))))+1,LEN(A1))))
like image 5
live-love Avatar answered Oct 16 '22 01:10

live-love