How to extract file name from path?
up vote
46
down vote
favorite
How do I extract the filename myfile.pdf
from C:Documentsmyfile.pdf
in VBA?
string vba
add a comment |
up vote
46
down vote
favorite
How do I extract the filename myfile.pdf
from C:Documentsmyfile.pdf
in VBA?
string vba
Try using the split function to get the file name from the path: MSDN link
– jonaspp
Nov 16 '09 at 16:44
add a comment |
up vote
46
down vote
favorite
up vote
46
down vote
favorite
How do I extract the filename myfile.pdf
from C:Documentsmyfile.pdf
in VBA?
string vba
How do I extract the filename myfile.pdf
from C:Documentsmyfile.pdf
in VBA?
string vba
string vba
edited Jul 5 '17 at 14:31
Smandoli
5,66633675
5,66633675
asked Nov 16 '09 at 16:39
Johan
8,579296287
8,579296287
Try using the split function to get the file name from the path: MSDN link
– jonaspp
Nov 16 '09 at 16:44
add a comment |
Try using the split function to get the file name from the path: MSDN link
– jonaspp
Nov 16 '09 at 16:44
Try using the split function to get the file name from the path: MSDN link
– jonaspp
Nov 16 '09 at 16:44
Try using the split function to get the file name from the path: MSDN link
– jonaspp
Nov 16 '09 at 16:44
add a comment |
15 Answers
15
active
oldest
votes
up vote
37
down vote
accepted
This is taken from snippets.dzone.com:
Function GetFilenameFromPath(ByVal strPath As String) As String
' Returns the rightmost characters of a string upto but not including the rightmost ''
' e.g. 'c:winntwin.ini' returns 'win.ini'
If Right$(strPath, 1) <> "" And Len(strPath) > 0 Then
GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
End If
End Function
1
Correct, but what if you're on a Mac? Unfortunately this is not a cross platform solution..
– Thomas Fankhauser
Feb 24 '13 at 14:01
3
Just replace the in the code with a /.
– Gonzalo
Feb 25 '13 at 5:40
1
Then it's broken on windows, right? I already figured it out to useApplication.PathSeparator
, but unfortunately on OSX VBA even returns paths in the old:
-notation. I had to write a function that converts those paths.
– Thomas Fankhauser
Feb 25 '13 at 17:07
3
This works, but is needlessly recursive, especially for VBA (which does not convert tail-recursion to a loop automatically).
– Mary
Jul 19 '13 at 18:58
4
IMHO, stackoverflow.com/a/1755577/481207 by Zen is a better answer. Code reuse, no recursion, no embedded constants.
– Matt
Jun 28 '15 at 21:33
|
show 2 more comments
up vote
109
down vote
The best way of working with files and directories in VBA for Office 2000/2003 is using the scripting library. Add a reference to Microsoft Scripting Runtime (Tools > References in the IDE).
Create a filesystem object and do all operations using that.
Dim fso as new FileSystemObject
Dim fileName As String
fileName = fso.GetFileName("c:any pathfile.txt")
The FileSystemObject is great. It offers a lot of features such as getting special folders (My documents, etc), creating, moving, copying, deleting files and directories in an object oriented manner. Check it out.
13
This answer beats the accepted answer by a mile.
– Bob Jansen
Dec 29 '14 at 8:28
6
In Excel VBA,Dim fileName As String; Dim fso as Object; Set fso = CreateObject("Scripting.FileSystemObject"); fileName = fso.GetFilename(path);
– IceArdor
Apr 27 '15 at 23:46
3
A word of warning, if you get a "User-defined type not defined" error you need to set a reference to the VB script run-time library. Load the VB Editor (ALT+F11), Select Tools > References from the drop-down menu, and from the list of available references tick the check box next to 'Microsoft Scripting Runtime' and click OK.
– Ian Stanway
Nov 6 '15 at 12:21
2
@Skrol29 every single Windows box in the world includes that library. Nothing to worry about. Accepted answer won't work on a Mac either. People that systematically late-bind the Scripting runtime don't know what they're doing, nor why. This answer is perfectly acceptable, and does beat the accepted answer by a mile. Or two.
– Mathieu Guindon
Jul 13 '17 at 20:00
3
@IceArdor Late-binding the Scripting Runtime buys you exactly nothing. You get a performance penalty for resolving the calls at run-time, and zero compile-time checks which means you make a typo and you won't know about it until you run the code, which will happily compile. Don't late-bind a library that's standard delivery on every single Windows machine since Win98.
– Mathieu Guindon
Jul 13 '17 at 20:05
|
show 2 more comments
up vote
41
down vote
Dir("C:Documentsmyfile.pdf")
will return the file name, but only if it exists.
1
+1 for "really short"
– golimar
Nov 13 '14 at 10:07
3
Bad because it assumes that the path is for a physical file that the program can read.
– Skrol29
Nov 6 '15 at 15:41
hi @Skrol29, could you please help to explain more on this?
– Harry Duong
Dec 17 '15 at 0:21
@HarryDuongDir
returns the file name, but only if the file actually exists at that location. If the file does not exist,Dir
return an empty string. If you know the file exists, such as when you prompt the user to select a file, then this is a quick and easy way to get the file name. If you don't know whether the file exists,Split
from @ArturPiwkowski is better. TwoSplits
will be faster than any string manipulation.
– Dick Kusleika
Dec 17 '15 at 16:48
@Harry Duong: The function Dir() does perform a scan on the computer to check the given mask. In this examples, the mask is the name of the expected file. If the file does not exist on the computer, the Dir() returns an empty value. But here is many cases when you what to extract the name from a path that does not physically exists. For example for a path of a file to be created, or a file just deleted before.
– Skrol29
Dec 22 '15 at 16:08
|
show 1 more comment
up vote
24
down vote
I've read through all the answers and I'd like to add one more that I think wins out because of its simplicity. Unlike the accepted answer this does not require recursion. It also does not require referencing a FileSystemObject.
Function FileNameFromPath(strFullPath As String) As String
FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, ""))
End Function
http://vba-tutorial.com/parsing-a-file-string-into-path-filename-and-extension/ has this code plus other functions for parsing out the file path, extension and even the filename without the extension.
1
The best for me : smart, short and does off-road.
– Skrol29
Nov 6 '15 at 15:51
2
+1 for simplicity - can even forego the function, and use the "=" line as-is, or in a loop, for multiple files.
– tahwos
Oct 3 '16 at 3:45
I prefer this one over any of the other answers. It's easily reusable in any other sub or function and doesn't require any fiddling with references
– mattlore
Sep 13 '17 at 17:53
add a comment |
up vote
9
down vote
Dim sFilePath$, sFileName$
sFileName = Split(sFilePath, "")(UBound(Split(sFilePath, "")))
Not so smart because it run twiceSplit(sFilePath, "")
.
– Skrol29
Nov 6 '15 at 15:39
add a comment |
up vote
4
down vote
If you want a more robust solution that will give you both the full folder's path AND the filename, here it is:
Dim strFileName As String, strFolderPath As String
Dim lngIndex As Long
Dim strPath() As String
strPath() = Split(OpenArgs, "") 'Put the Parts of our path into an array
lngIndex = UBound(strPath)
strFileName = strPath(lngIndex) 'Get the File Name from our array
strPath(lngIndex) = "" 'Remove the File Name from our array
strFolderPath = Join(strPath, "") 'Rebuild our path from our array
Or as a sub/function:
Private Sub SeparatePathAndFile(ByRef io_strFolderPath As String, ByRef o_strFileName As String)
Dim strPath() As String
Dim lngIndex As Long
strPath() = Split(io_strFolderPath, "") 'Put the Parts of our path into an array
lngIndex = UBound(strPath)
o_strFileName = strPath(lngIndex) 'Get the File Name from our array
strPath(lngIndex) = "" 'Remove the File Name from our array
io_strFolderPath = Join(strPath, "") 'Rebuild our path from our array
End Sub
You pass the first parameter with the full path of the file and it will be set to the folder's path while the second parameter will be set to the file's name.
add a comment |
up vote
3
down vote
To get the file name in an excel macro is:
filname = Mid(spth, InStrRev(spth, "", Len(spth)) + 1, Len(spth))
MsgBox Mid(filname, 1, InStr(filname, ".") - 1)
add a comment |
up vote
3
down vote
I can't believe how overcomplicated some of these answers are... (no offence!)
Here's a single-line function that will get the job done:
Function getFName(pf)As String:getFName=Mid(pf,InStrRev(pf,"")+1):End Function
Function getPath(pf)As String:getPath=Left(pf,InStrRev(pf,"")):End Function
Examples:
add a comment |
up vote
2
down vote
Here's a simple VBA solution I wrote that works with Windows, Unix, Mac, and URL paths.
sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)
sFolderName = Left(sPath, Len(sPath) - Len(sFileName))
You can test the output using this code:
'Visual Basic for Applications
http = "https://www.server.com/docs/Letter.txt"
unix = "/home/user/docs/Letter.txt"
dos = "C:userdocsLetter.txt"
win = "\Server01userdocsLetter.txt"
blank = ""
sPath = unix
sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)
sFolderName = Left(sPath, Len(sPath) - Len(sFileName))
Debug.print "Folder: " & sFolderName & " File: " & sFileName
Also see: Wikipedia - Path (computing)
add a comment |
up vote
2
down vote
The simplest approach if you are sure the file physically exists on the disk:
Dim fileName, filePath As String
filePath = "C:Documentsmyfile.pdf"
fileName = Dir(filePath)
If you are not sure about existence of file or just want to extract filename from a given path then, simplest approach is:
fileName = Mid(filePath, InStrRev(filePath, "") + 1)
add a comment |
up vote
1
down vote
Here's an alternative 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))))
add a comment |
up vote
0
down vote
I needed the path, not the filename.
So to extract the file path in code:
JustPath = Left(sFileP, Len(sFileP) - Len(Split(sFileP, "")(UBound(Split(sFileP, "")))))
add a comment |
up vote
0
down vote
This gleaned from Twiggy @ http://archive.atomicmpc.com.au and other places:
'since the file name and path were used several times in code
'variables were made public
Public FName As Variant, Filename As String, Path As String
Sub xxx()
...
If Not GetFileName = 1 Then Exit Sub '
...
End Sub
Private Function GetFileName()
GetFileName = 0 'used for error handling at call point in case user cancels
FName = Application.GetOpenFilename("Ramp log file (*.txt), *.txt")
If Not VarType(FName) = vbBoolean Then GetFileName = 1 'to assure selection was made
Filename = Split(FName, "")(UBound(Split(FName, ""))) 'results in file name
Path = Left(FName, InStrRev(FName, "")) 'results in path
End Function
add a comment |
up vote
0
down vote
Function file_name_only(file_path As String) As String
Dim temp As Variant
temp = Split(file_path, Application.PathSeparator)
file_name_only = temp(UBound(temp))
End Function
- here you give your file name as input of the function
- the split function of VBA splits the path in different portion by using "" as path separator & stores them in an array named "temp"
- the UBound() finds the max item number of array and finally assigns the result to "file_name_only" function
Hope this will be helpful.
add a comment |
up vote
-1
down vote
Dim nme As String = My.Computer.FileSystem.GetFileInfo(pathFicheiro).Name
Dim dirc As String = My.Computer.FileSystem.GetFileInfo(nomeFicheiro).Directory
Although your answer may work for the question, could you please add some explanation of what is doing?
– Ivan
Aug 25 '15 at 12:00
This is better solution. It extracs filename and directory from given path pathFicheiro. There is no need for nomeFicheiro as you could just use pathFicheiro. pathFicheiro = FILENAME variable
– user1054844
Nov 15 '16 at 9:25
Sorry but unless I'm missing something, this is .net, so it doesn't answer the vba question.
– ashleedawg
Apr 25 at 4:44
add a comment |
15 Answers
15
active
oldest
votes
15 Answers
15
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
37
down vote
accepted
This is taken from snippets.dzone.com:
Function GetFilenameFromPath(ByVal strPath As String) As String
' Returns the rightmost characters of a string upto but not including the rightmost ''
' e.g. 'c:winntwin.ini' returns 'win.ini'
If Right$(strPath, 1) <> "" And Len(strPath) > 0 Then
GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
End If
End Function
1
Correct, but what if you're on a Mac? Unfortunately this is not a cross platform solution..
– Thomas Fankhauser
Feb 24 '13 at 14:01
3
Just replace the in the code with a /.
– Gonzalo
Feb 25 '13 at 5:40
1
Then it's broken on windows, right? I already figured it out to useApplication.PathSeparator
, but unfortunately on OSX VBA even returns paths in the old:
-notation. I had to write a function that converts those paths.
– Thomas Fankhauser
Feb 25 '13 at 17:07
3
This works, but is needlessly recursive, especially for VBA (which does not convert tail-recursion to a loop automatically).
– Mary
Jul 19 '13 at 18:58
4
IMHO, stackoverflow.com/a/1755577/481207 by Zen is a better answer. Code reuse, no recursion, no embedded constants.
– Matt
Jun 28 '15 at 21:33
|
show 2 more comments
up vote
37
down vote
accepted
This is taken from snippets.dzone.com:
Function GetFilenameFromPath(ByVal strPath As String) As String
' Returns the rightmost characters of a string upto but not including the rightmost ''
' e.g. 'c:winntwin.ini' returns 'win.ini'
If Right$(strPath, 1) <> "" And Len(strPath) > 0 Then
GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
End If
End Function
1
Correct, but what if you're on a Mac? Unfortunately this is not a cross platform solution..
– Thomas Fankhauser
Feb 24 '13 at 14:01
3
Just replace the in the code with a /.
– Gonzalo
Feb 25 '13 at 5:40
1
Then it's broken on windows, right? I already figured it out to useApplication.PathSeparator
, but unfortunately on OSX VBA even returns paths in the old:
-notation. I had to write a function that converts those paths.
– Thomas Fankhauser
Feb 25 '13 at 17:07
3
This works, but is needlessly recursive, especially for VBA (which does not convert tail-recursion to a loop automatically).
– Mary
Jul 19 '13 at 18:58
4
IMHO, stackoverflow.com/a/1755577/481207 by Zen is a better answer. Code reuse, no recursion, no embedded constants.
– Matt
Jun 28 '15 at 21:33
|
show 2 more comments
up vote
37
down vote
accepted
up vote
37
down vote
accepted
This is taken from snippets.dzone.com:
Function GetFilenameFromPath(ByVal strPath As String) As String
' Returns the rightmost characters of a string upto but not including the rightmost ''
' e.g. 'c:winntwin.ini' returns 'win.ini'
If Right$(strPath, 1) <> "" And Len(strPath) > 0 Then
GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
End If
End Function
This is taken from snippets.dzone.com:
Function GetFilenameFromPath(ByVal strPath As String) As String
' Returns the rightmost characters of a string upto but not including the rightmost ''
' e.g. 'c:winntwin.ini' returns 'win.ini'
If Right$(strPath, 1) <> "" And Len(strPath) > 0 Then
GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
End If
End Function
answered Nov 16 '09 at 16:43
Gonzalo
17.3k35769
17.3k35769
1
Correct, but what if you're on a Mac? Unfortunately this is not a cross platform solution..
– Thomas Fankhauser
Feb 24 '13 at 14:01
3
Just replace the in the code with a /.
– Gonzalo
Feb 25 '13 at 5:40
1
Then it's broken on windows, right? I already figured it out to useApplication.PathSeparator
, but unfortunately on OSX VBA even returns paths in the old:
-notation. I had to write a function that converts those paths.
– Thomas Fankhauser
Feb 25 '13 at 17:07
3
This works, but is needlessly recursive, especially for VBA (which does not convert tail-recursion to a loop automatically).
– Mary
Jul 19 '13 at 18:58
4
IMHO, stackoverflow.com/a/1755577/481207 by Zen is a better answer. Code reuse, no recursion, no embedded constants.
– Matt
Jun 28 '15 at 21:33
|
show 2 more comments
1
Correct, but what if you're on a Mac? Unfortunately this is not a cross platform solution..
– Thomas Fankhauser
Feb 24 '13 at 14:01
3
Just replace the in the code with a /.
– Gonzalo
Feb 25 '13 at 5:40
1
Then it's broken on windows, right? I already figured it out to useApplication.PathSeparator
, but unfortunately on OSX VBA even returns paths in the old:
-notation. I had to write a function that converts those paths.
– Thomas Fankhauser
Feb 25 '13 at 17:07
3
This works, but is needlessly recursive, especially for VBA (which does not convert tail-recursion to a loop automatically).
– Mary
Jul 19 '13 at 18:58
4
IMHO, stackoverflow.com/a/1755577/481207 by Zen is a better answer. Code reuse, no recursion, no embedded constants.
– Matt
Jun 28 '15 at 21:33
1
1
Correct, but what if you're on a Mac? Unfortunately this is not a cross platform solution..
– Thomas Fankhauser
Feb 24 '13 at 14:01
Correct, but what if you're on a Mac? Unfortunately this is not a cross platform solution..
– Thomas Fankhauser
Feb 24 '13 at 14:01
3
3
Just replace the in the code with a /.
– Gonzalo
Feb 25 '13 at 5:40
Just replace the in the code with a /.
– Gonzalo
Feb 25 '13 at 5:40
1
1
Then it's broken on windows, right? I already figured it out to use
Application.PathSeparator
, but unfortunately on OSX VBA even returns paths in the old :
-notation. I had to write a function that converts those paths.– Thomas Fankhauser
Feb 25 '13 at 17:07
Then it's broken on windows, right? I already figured it out to use
Application.PathSeparator
, but unfortunately on OSX VBA even returns paths in the old :
-notation. I had to write a function that converts those paths.– Thomas Fankhauser
Feb 25 '13 at 17:07
3
3
This works, but is needlessly recursive, especially for VBA (which does not convert tail-recursion to a loop automatically).
– Mary
Jul 19 '13 at 18:58
This works, but is needlessly recursive, especially for VBA (which does not convert tail-recursion to a loop automatically).
– Mary
Jul 19 '13 at 18:58
4
4
IMHO, stackoverflow.com/a/1755577/481207 by Zen is a better answer. Code reuse, no recursion, no embedded constants.
– Matt
Jun 28 '15 at 21:33
IMHO, stackoverflow.com/a/1755577/481207 by Zen is a better answer. Code reuse, no recursion, no embedded constants.
– Matt
Jun 28 '15 at 21:33
|
show 2 more comments
up vote
109
down vote
The best way of working with files and directories in VBA for Office 2000/2003 is using the scripting library. Add a reference to Microsoft Scripting Runtime (Tools > References in the IDE).
Create a filesystem object and do all operations using that.
Dim fso as new FileSystemObject
Dim fileName As String
fileName = fso.GetFileName("c:any pathfile.txt")
The FileSystemObject is great. It offers a lot of features such as getting special folders (My documents, etc), creating, moving, copying, deleting files and directories in an object oriented manner. Check it out.
13
This answer beats the accepted answer by a mile.
– Bob Jansen
Dec 29 '14 at 8:28
6
In Excel VBA,Dim fileName As String; Dim fso as Object; Set fso = CreateObject("Scripting.FileSystemObject"); fileName = fso.GetFilename(path);
– IceArdor
Apr 27 '15 at 23:46
3
A word of warning, if you get a "User-defined type not defined" error you need to set a reference to the VB script run-time library. Load the VB Editor (ALT+F11), Select Tools > References from the drop-down menu, and from the list of available references tick the check box next to 'Microsoft Scripting Runtime' and click OK.
– Ian Stanway
Nov 6 '15 at 12:21
2
@Skrol29 every single Windows box in the world includes that library. Nothing to worry about. Accepted answer won't work on a Mac either. People that systematically late-bind the Scripting runtime don't know what they're doing, nor why. This answer is perfectly acceptable, and does beat the accepted answer by a mile. Or two.
– Mathieu Guindon
Jul 13 '17 at 20:00
3
@IceArdor Late-binding the Scripting Runtime buys you exactly nothing. You get a performance penalty for resolving the calls at run-time, and zero compile-time checks which means you make a typo and you won't know about it until you run the code, which will happily compile. Don't late-bind a library that's standard delivery on every single Windows machine since Win98.
– Mathieu Guindon
Jul 13 '17 at 20:05
|
show 2 more comments
up vote
109
down vote
The best way of working with files and directories in VBA for Office 2000/2003 is using the scripting library. Add a reference to Microsoft Scripting Runtime (Tools > References in the IDE).
Create a filesystem object and do all operations using that.
Dim fso as new FileSystemObject
Dim fileName As String
fileName = fso.GetFileName("c:any pathfile.txt")
The FileSystemObject is great. It offers a lot of features such as getting special folders (My documents, etc), creating, moving, copying, deleting files and directories in an object oriented manner. Check it out.
13
This answer beats the accepted answer by a mile.
– Bob Jansen
Dec 29 '14 at 8:28
6
In Excel VBA,Dim fileName As String; Dim fso as Object; Set fso = CreateObject("Scripting.FileSystemObject"); fileName = fso.GetFilename(path);
– IceArdor
Apr 27 '15 at 23:46
3
A word of warning, if you get a "User-defined type not defined" error you need to set a reference to the VB script run-time library. Load the VB Editor (ALT+F11), Select Tools > References from the drop-down menu, and from the list of available references tick the check box next to 'Microsoft Scripting Runtime' and click OK.
– Ian Stanway
Nov 6 '15 at 12:21
2
@Skrol29 every single Windows box in the world includes that library. Nothing to worry about. Accepted answer won't work on a Mac either. People that systematically late-bind the Scripting runtime don't know what they're doing, nor why. This answer is perfectly acceptable, and does beat the accepted answer by a mile. Or two.
– Mathieu Guindon
Jul 13 '17 at 20:00
3
@IceArdor Late-binding the Scripting Runtime buys you exactly nothing. You get a performance penalty for resolving the calls at run-time, and zero compile-time checks which means you make a typo and you won't know about it until you run the code, which will happily compile. Don't late-bind a library that's standard delivery on every single Windows machine since Win98.
– Mathieu Guindon
Jul 13 '17 at 20:05
|
show 2 more comments
up vote
109
down vote
up vote
109
down vote
The best way of working with files and directories in VBA for Office 2000/2003 is using the scripting library. Add a reference to Microsoft Scripting Runtime (Tools > References in the IDE).
Create a filesystem object and do all operations using that.
Dim fso as new FileSystemObject
Dim fileName As String
fileName = fso.GetFileName("c:any pathfile.txt")
The FileSystemObject is great. It offers a lot of features such as getting special folders (My documents, etc), creating, moving, copying, deleting files and directories in an object oriented manner. Check it out.
The best way of working with files and directories in VBA for Office 2000/2003 is using the scripting library. Add a reference to Microsoft Scripting Runtime (Tools > References in the IDE).
Create a filesystem object and do all operations using that.
Dim fso as new FileSystemObject
Dim fileName As String
fileName = fso.GetFileName("c:any pathfile.txt")
The FileSystemObject is great. It offers a lot of features such as getting special folders (My documents, etc), creating, moving, copying, deleting files and directories in an object oriented manner. Check it out.
answered Nov 18 '09 at 12:13
Zen
1,3143913
1,3143913
13
This answer beats the accepted answer by a mile.
– Bob Jansen
Dec 29 '14 at 8:28
6
In Excel VBA,Dim fileName As String; Dim fso as Object; Set fso = CreateObject("Scripting.FileSystemObject"); fileName = fso.GetFilename(path);
– IceArdor
Apr 27 '15 at 23:46
3
A word of warning, if you get a "User-defined type not defined" error you need to set a reference to the VB script run-time library. Load the VB Editor (ALT+F11), Select Tools > References from the drop-down menu, and from the list of available references tick the check box next to 'Microsoft Scripting Runtime' and click OK.
– Ian Stanway
Nov 6 '15 at 12:21
2
@Skrol29 every single Windows box in the world includes that library. Nothing to worry about. Accepted answer won't work on a Mac either. People that systematically late-bind the Scripting runtime don't know what they're doing, nor why. This answer is perfectly acceptable, and does beat the accepted answer by a mile. Or two.
– Mathieu Guindon
Jul 13 '17 at 20:00
3
@IceArdor Late-binding the Scripting Runtime buys you exactly nothing. You get a performance penalty for resolving the calls at run-time, and zero compile-time checks which means you make a typo and you won't know about it until you run the code, which will happily compile. Don't late-bind a library that's standard delivery on every single Windows machine since Win98.
– Mathieu Guindon
Jul 13 '17 at 20:05
|
show 2 more comments
13
This answer beats the accepted answer by a mile.
– Bob Jansen
Dec 29 '14 at 8:28
6
In Excel VBA,Dim fileName As String; Dim fso as Object; Set fso = CreateObject("Scripting.FileSystemObject"); fileName = fso.GetFilename(path);
– IceArdor
Apr 27 '15 at 23:46
3
A word of warning, if you get a "User-defined type not defined" error you need to set a reference to the VB script run-time library. Load the VB Editor (ALT+F11), Select Tools > References from the drop-down menu, and from the list of available references tick the check box next to 'Microsoft Scripting Runtime' and click OK.
– Ian Stanway
Nov 6 '15 at 12:21
2
@Skrol29 every single Windows box in the world includes that library. Nothing to worry about. Accepted answer won't work on a Mac either. People that systematically late-bind the Scripting runtime don't know what they're doing, nor why. This answer is perfectly acceptable, and does beat the accepted answer by a mile. Or two.
– Mathieu Guindon
Jul 13 '17 at 20:00
3
@IceArdor Late-binding the Scripting Runtime buys you exactly nothing. You get a performance penalty for resolving the calls at run-time, and zero compile-time checks which means you make a typo and you won't know about it until you run the code, which will happily compile. Don't late-bind a library that's standard delivery on every single Windows machine since Win98.
– Mathieu Guindon
Jul 13 '17 at 20:05
13
13
This answer beats the accepted answer by a mile.
– Bob Jansen
Dec 29 '14 at 8:28
This answer beats the accepted answer by a mile.
– Bob Jansen
Dec 29 '14 at 8:28
6
6
In Excel VBA,
Dim fileName As String; Dim fso as Object; Set fso = CreateObject("Scripting.FileSystemObject"); fileName = fso.GetFilename(path);
– IceArdor
Apr 27 '15 at 23:46
In Excel VBA,
Dim fileName As String; Dim fso as Object; Set fso = CreateObject("Scripting.FileSystemObject"); fileName = fso.GetFilename(path);
– IceArdor
Apr 27 '15 at 23:46
3
3
A word of warning, if you get a "User-defined type not defined" error you need to set a reference to the VB script run-time library. Load the VB Editor (ALT+F11), Select Tools > References from the drop-down menu, and from the list of available references tick the check box next to 'Microsoft Scripting Runtime' and click OK.
– Ian Stanway
Nov 6 '15 at 12:21
A word of warning, if you get a "User-defined type not defined" error you need to set a reference to the VB script run-time library. Load the VB Editor (ALT+F11), Select Tools > References from the drop-down menu, and from the list of available references tick the check box next to 'Microsoft Scripting Runtime' and click OK.
– Ian Stanway
Nov 6 '15 at 12:21
2
2
@Skrol29 every single Windows box in the world includes that library. Nothing to worry about. Accepted answer won't work on a Mac either. People that systematically late-bind the Scripting runtime don't know what they're doing, nor why. This answer is perfectly acceptable, and does beat the accepted answer by a mile. Or two.
– Mathieu Guindon
Jul 13 '17 at 20:00
@Skrol29 every single Windows box in the world includes that library. Nothing to worry about. Accepted answer won't work on a Mac either. People that systematically late-bind the Scripting runtime don't know what they're doing, nor why. This answer is perfectly acceptable, and does beat the accepted answer by a mile. Or two.
– Mathieu Guindon
Jul 13 '17 at 20:00
3
3
@IceArdor Late-binding the Scripting Runtime buys you exactly nothing. You get a performance penalty for resolving the calls at run-time, and zero compile-time checks which means you make a typo and you won't know about it until you run the code, which will happily compile. Don't late-bind a library that's standard delivery on every single Windows machine since Win98.
– Mathieu Guindon
Jul 13 '17 at 20:05
@IceArdor Late-binding the Scripting Runtime buys you exactly nothing. You get a performance penalty for resolving the calls at run-time, and zero compile-time checks which means you make a typo and you won't know about it until you run the code, which will happily compile. Don't late-bind a library that's standard delivery on every single Windows machine since Win98.
– Mathieu Guindon
Jul 13 '17 at 20:05
|
show 2 more comments
up vote
41
down vote
Dir("C:Documentsmyfile.pdf")
will return the file name, but only if it exists.
1
+1 for "really short"
– golimar
Nov 13 '14 at 10:07
3
Bad because it assumes that the path is for a physical file that the program can read.
– Skrol29
Nov 6 '15 at 15:41
hi @Skrol29, could you please help to explain more on this?
– Harry Duong
Dec 17 '15 at 0:21
@HarryDuongDir
returns the file name, but only if the file actually exists at that location. If the file does not exist,Dir
return an empty string. If you know the file exists, such as when you prompt the user to select a file, then this is a quick and easy way to get the file name. If you don't know whether the file exists,Split
from @ArturPiwkowski is better. TwoSplits
will be faster than any string manipulation.
– Dick Kusleika
Dec 17 '15 at 16:48
@Harry Duong: The function Dir() does perform a scan on the computer to check the given mask. In this examples, the mask is the name of the expected file. If the file does not exist on the computer, the Dir() returns an empty value. But here is many cases when you what to extract the name from a path that does not physically exists. For example for a path of a file to be created, or a file just deleted before.
– Skrol29
Dec 22 '15 at 16:08
|
show 1 more comment
up vote
41
down vote
Dir("C:Documentsmyfile.pdf")
will return the file name, but only if it exists.
1
+1 for "really short"
– golimar
Nov 13 '14 at 10:07
3
Bad because it assumes that the path is for a physical file that the program can read.
– Skrol29
Nov 6 '15 at 15:41
hi @Skrol29, could you please help to explain more on this?
– Harry Duong
Dec 17 '15 at 0:21
@HarryDuongDir
returns the file name, but only if the file actually exists at that location. If the file does not exist,Dir
return an empty string. If you know the file exists, such as when you prompt the user to select a file, then this is a quick and easy way to get the file name. If you don't know whether the file exists,Split
from @ArturPiwkowski is better. TwoSplits
will be faster than any string manipulation.
– Dick Kusleika
Dec 17 '15 at 16:48
@Harry Duong: The function Dir() does perform a scan on the computer to check the given mask. In this examples, the mask is the name of the expected file. If the file does not exist on the computer, the Dir() returns an empty value. But here is many cases when you what to extract the name from a path that does not physically exists. For example for a path of a file to be created, or a file just deleted before.
– Skrol29
Dec 22 '15 at 16:08
|
show 1 more comment
up vote
41
down vote
up vote
41
down vote
Dir("C:Documentsmyfile.pdf")
will return the file name, but only if it exists.
Dir("C:Documentsmyfile.pdf")
will return the file name, but only if it exists.
edited Oct 5 '13 at 13:29
answered Nov 22 '09 at 13:53
Dick Kusleika
27.3k33559
27.3k33559
1
+1 for "really short"
– golimar
Nov 13 '14 at 10:07
3
Bad because it assumes that the path is for a physical file that the program can read.
– Skrol29
Nov 6 '15 at 15:41
hi @Skrol29, could you please help to explain more on this?
– Harry Duong
Dec 17 '15 at 0:21
@HarryDuongDir
returns the file name, but only if the file actually exists at that location. If the file does not exist,Dir
return an empty string. If you know the file exists, such as when you prompt the user to select a file, then this is a quick and easy way to get the file name. If you don't know whether the file exists,Split
from @ArturPiwkowski is better. TwoSplits
will be faster than any string manipulation.
– Dick Kusleika
Dec 17 '15 at 16:48
@Harry Duong: The function Dir() does perform a scan on the computer to check the given mask. In this examples, the mask is the name of the expected file. If the file does not exist on the computer, the Dir() returns an empty value. But here is many cases when you what to extract the name from a path that does not physically exists. For example for a path of a file to be created, or a file just deleted before.
– Skrol29
Dec 22 '15 at 16:08
|
show 1 more comment
1
+1 for "really short"
– golimar
Nov 13 '14 at 10:07
3
Bad because it assumes that the path is for a physical file that the program can read.
– Skrol29
Nov 6 '15 at 15:41
hi @Skrol29, could you please help to explain more on this?
– Harry Duong
Dec 17 '15 at 0:21
@HarryDuongDir
returns the file name, but only if the file actually exists at that location. If the file does not exist,Dir
return an empty string. If you know the file exists, such as when you prompt the user to select a file, then this is a quick and easy way to get the file name. If you don't know whether the file exists,Split
from @ArturPiwkowski is better. TwoSplits
will be faster than any string manipulation.
– Dick Kusleika
Dec 17 '15 at 16:48
@Harry Duong: The function Dir() does perform a scan on the computer to check the given mask. In this examples, the mask is the name of the expected file. If the file does not exist on the computer, the Dir() returns an empty value. But here is many cases when you what to extract the name from a path that does not physically exists. For example for a path of a file to be created, or a file just deleted before.
– Skrol29
Dec 22 '15 at 16:08
1
1
+1 for "really short"
– golimar
Nov 13 '14 at 10:07
+1 for "really short"
– golimar
Nov 13 '14 at 10:07
3
3
Bad because it assumes that the path is for a physical file that the program can read.
– Skrol29
Nov 6 '15 at 15:41
Bad because it assumes that the path is for a physical file that the program can read.
– Skrol29
Nov 6 '15 at 15:41
hi @Skrol29, could you please help to explain more on this?
– Harry Duong
Dec 17 '15 at 0:21
hi @Skrol29, could you please help to explain more on this?
– Harry Duong
Dec 17 '15 at 0:21
@HarryDuong
Dir
returns the file name, but only if the file actually exists at that location. If the file does not exist, Dir
return an empty string. If you know the file exists, such as when you prompt the user to select a file, then this is a quick and easy way to get the file name. If you don't know whether the file exists, Split
from @ArturPiwkowski is better. Two Splits
will be faster than any string manipulation.– Dick Kusleika
Dec 17 '15 at 16:48
@HarryDuong
Dir
returns the file name, but only if the file actually exists at that location. If the file does not exist, Dir
return an empty string. If you know the file exists, such as when you prompt the user to select a file, then this is a quick and easy way to get the file name. If you don't know whether the file exists, Split
from @ArturPiwkowski is better. Two Splits
will be faster than any string manipulation.– Dick Kusleika
Dec 17 '15 at 16:48
@Harry Duong: The function Dir() does perform a scan on the computer to check the given mask. In this examples, the mask is the name of the expected file. If the file does not exist on the computer, the Dir() returns an empty value. But here is many cases when you what to extract the name from a path that does not physically exists. For example for a path of a file to be created, or a file just deleted before.
– Skrol29
Dec 22 '15 at 16:08
@Harry Duong: The function Dir() does perform a scan on the computer to check the given mask. In this examples, the mask is the name of the expected file. If the file does not exist on the computer, the Dir() returns an empty value. But here is many cases when you what to extract the name from a path that does not physically exists. For example for a path of a file to be created, or a file just deleted before.
– Skrol29
Dec 22 '15 at 16:08
|
show 1 more comment
up vote
24
down vote
I've read through all the answers and I'd like to add one more that I think wins out because of its simplicity. Unlike the accepted answer this does not require recursion. It also does not require referencing a FileSystemObject.
Function FileNameFromPath(strFullPath As String) As String
FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, ""))
End Function
http://vba-tutorial.com/parsing-a-file-string-into-path-filename-and-extension/ has this code plus other functions for parsing out the file path, extension and even the filename without the extension.
1
The best for me : smart, short and does off-road.
– Skrol29
Nov 6 '15 at 15:51
2
+1 for simplicity - can even forego the function, and use the "=" line as-is, or in a loop, for multiple files.
– tahwos
Oct 3 '16 at 3:45
I prefer this one over any of the other answers. It's easily reusable in any other sub or function and doesn't require any fiddling with references
– mattlore
Sep 13 '17 at 17:53
add a comment |
up vote
24
down vote
I've read through all the answers and I'd like to add one more that I think wins out because of its simplicity. Unlike the accepted answer this does not require recursion. It also does not require referencing a FileSystemObject.
Function FileNameFromPath(strFullPath As String) As String
FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, ""))
End Function
http://vba-tutorial.com/parsing-a-file-string-into-path-filename-and-extension/ has this code plus other functions for parsing out the file path, extension and even the filename without the extension.
1
The best for me : smart, short and does off-road.
– Skrol29
Nov 6 '15 at 15:51
2
+1 for simplicity - can even forego the function, and use the "=" line as-is, or in a loop, for multiple files.
– tahwos
Oct 3 '16 at 3:45
I prefer this one over any of the other answers. It's easily reusable in any other sub or function and doesn't require any fiddling with references
– mattlore
Sep 13 '17 at 17:53
add a comment |
up vote
24
down vote
up vote
24
down vote
I've read through all the answers and I'd like to add one more that I think wins out because of its simplicity. Unlike the accepted answer this does not require recursion. It also does not require referencing a FileSystemObject.
Function FileNameFromPath(strFullPath As String) As String
FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, ""))
End Function
http://vba-tutorial.com/parsing-a-file-string-into-path-filename-and-extension/ has this code plus other functions for parsing out the file path, extension and even the filename without the extension.
I've read through all the answers and I'd like to add one more that I think wins out because of its simplicity. Unlike the accepted answer this does not require recursion. It also does not require referencing a FileSystemObject.
Function FileNameFromPath(strFullPath As String) As String
FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, ""))
End Function
http://vba-tutorial.com/parsing-a-file-string-into-path-filename-and-extension/ has this code plus other functions for parsing out the file path, extension and even the filename without the extension.
answered Oct 5 '13 at 1:01
user2780436
37429
37429
1
The best for me : smart, short and does off-road.
– Skrol29
Nov 6 '15 at 15:51
2
+1 for simplicity - can even forego the function, and use the "=" line as-is, or in a loop, for multiple files.
– tahwos
Oct 3 '16 at 3:45
I prefer this one over any of the other answers. It's easily reusable in any other sub or function and doesn't require any fiddling with references
– mattlore
Sep 13 '17 at 17:53
add a comment |
1
The best for me : smart, short and does off-road.
– Skrol29
Nov 6 '15 at 15:51
2
+1 for simplicity - can even forego the function, and use the "=" line as-is, or in a loop, for multiple files.
– tahwos
Oct 3 '16 at 3:45
I prefer this one over any of the other answers. It's easily reusable in any other sub or function and doesn't require any fiddling with references
– mattlore
Sep 13 '17 at 17:53
1
1
The best for me : smart, short and does off-road.
– Skrol29
Nov 6 '15 at 15:51
The best for me : smart, short and does off-road.
– Skrol29
Nov 6 '15 at 15:51
2
2
+1 for simplicity - can even forego the function, and use the "=" line as-is, or in a loop, for multiple files.
– tahwos
Oct 3 '16 at 3:45
+1 for simplicity - can even forego the function, and use the "=" line as-is, or in a loop, for multiple files.
– tahwos
Oct 3 '16 at 3:45
I prefer this one over any of the other answers. It's easily reusable in any other sub or function and doesn't require any fiddling with references
– mattlore
Sep 13 '17 at 17:53
I prefer this one over any of the other answers. It's easily reusable in any other sub or function and doesn't require any fiddling with references
– mattlore
Sep 13 '17 at 17:53
add a comment |
up vote
9
down vote
Dim sFilePath$, sFileName$
sFileName = Split(sFilePath, "")(UBound(Split(sFilePath, "")))
Not so smart because it run twiceSplit(sFilePath, "")
.
– Skrol29
Nov 6 '15 at 15:39
add a comment |
up vote
9
down vote
Dim sFilePath$, sFileName$
sFileName = Split(sFilePath, "")(UBound(Split(sFilePath, "")))
Not so smart because it run twiceSplit(sFilePath, "")
.
– Skrol29
Nov 6 '15 at 15:39
add a comment |
up vote
9
down vote
up vote
9
down vote
Dim sFilePath$, sFileName$
sFileName = Split(sFilePath, "")(UBound(Split(sFilePath, "")))
Dim sFilePath$, sFileName$
sFileName = Split(sFilePath, "")(UBound(Split(sFilePath, "")))
edited Feb 8 '13 at 15:42
Jon Egerton
29.5k1070112
29.5k1070112
answered Feb 8 '13 at 15:24
Artur Piwkowski
9911
9911
Not so smart because it run twiceSplit(sFilePath, "")
.
– Skrol29
Nov 6 '15 at 15:39
add a comment |
Not so smart because it run twiceSplit(sFilePath, "")
.
– Skrol29
Nov 6 '15 at 15:39
Not so smart because it run twice
Split(sFilePath, "")
.– Skrol29
Nov 6 '15 at 15:39
Not so smart because it run twice
Split(sFilePath, "")
.– Skrol29
Nov 6 '15 at 15:39
add a comment |
up vote
4
down vote
If you want a more robust solution that will give you both the full folder's path AND the filename, here it is:
Dim strFileName As String, strFolderPath As String
Dim lngIndex As Long
Dim strPath() As String
strPath() = Split(OpenArgs, "") 'Put the Parts of our path into an array
lngIndex = UBound(strPath)
strFileName = strPath(lngIndex) 'Get the File Name from our array
strPath(lngIndex) = "" 'Remove the File Name from our array
strFolderPath = Join(strPath, "") 'Rebuild our path from our array
Or as a sub/function:
Private Sub SeparatePathAndFile(ByRef io_strFolderPath As String, ByRef o_strFileName As String)
Dim strPath() As String
Dim lngIndex As Long
strPath() = Split(io_strFolderPath, "") 'Put the Parts of our path into an array
lngIndex = UBound(strPath)
o_strFileName = strPath(lngIndex) 'Get the File Name from our array
strPath(lngIndex) = "" 'Remove the File Name from our array
io_strFolderPath = Join(strPath, "") 'Rebuild our path from our array
End Sub
You pass the first parameter with the full path of the file and it will be set to the folder's path while the second parameter will be set to the file's name.
add a comment |
up vote
4
down vote
If you want a more robust solution that will give you both the full folder's path AND the filename, here it is:
Dim strFileName As String, strFolderPath As String
Dim lngIndex As Long
Dim strPath() As String
strPath() = Split(OpenArgs, "") 'Put the Parts of our path into an array
lngIndex = UBound(strPath)
strFileName = strPath(lngIndex) 'Get the File Name from our array
strPath(lngIndex) = "" 'Remove the File Name from our array
strFolderPath = Join(strPath, "") 'Rebuild our path from our array
Or as a sub/function:
Private Sub SeparatePathAndFile(ByRef io_strFolderPath As String, ByRef o_strFileName As String)
Dim strPath() As String
Dim lngIndex As Long
strPath() = Split(io_strFolderPath, "") 'Put the Parts of our path into an array
lngIndex = UBound(strPath)
o_strFileName = strPath(lngIndex) 'Get the File Name from our array
strPath(lngIndex) = "" 'Remove the File Name from our array
io_strFolderPath = Join(strPath, "") 'Rebuild our path from our array
End Sub
You pass the first parameter with the full path of the file and it will be set to the folder's path while the second parameter will be set to the file's name.
add a comment |
up vote
4
down vote
up vote
4
down vote
If you want a more robust solution that will give you both the full folder's path AND the filename, here it is:
Dim strFileName As String, strFolderPath As String
Dim lngIndex As Long
Dim strPath() As String
strPath() = Split(OpenArgs, "") 'Put the Parts of our path into an array
lngIndex = UBound(strPath)
strFileName = strPath(lngIndex) 'Get the File Name from our array
strPath(lngIndex) = "" 'Remove the File Name from our array
strFolderPath = Join(strPath, "") 'Rebuild our path from our array
Or as a sub/function:
Private Sub SeparatePathAndFile(ByRef io_strFolderPath As String, ByRef o_strFileName As String)
Dim strPath() As String
Dim lngIndex As Long
strPath() = Split(io_strFolderPath, "") 'Put the Parts of our path into an array
lngIndex = UBound(strPath)
o_strFileName = strPath(lngIndex) 'Get the File Name from our array
strPath(lngIndex) = "" 'Remove the File Name from our array
io_strFolderPath = Join(strPath, "") 'Rebuild our path from our array
End Sub
You pass the first parameter with the full path of the file and it will be set to the folder's path while the second parameter will be set to the file's name.
If you want a more robust solution that will give you both the full folder's path AND the filename, here it is:
Dim strFileName As String, strFolderPath As String
Dim lngIndex As Long
Dim strPath() As String
strPath() = Split(OpenArgs, "") 'Put the Parts of our path into an array
lngIndex = UBound(strPath)
strFileName = strPath(lngIndex) 'Get the File Name from our array
strPath(lngIndex) = "" 'Remove the File Name from our array
strFolderPath = Join(strPath, "") 'Rebuild our path from our array
Or as a sub/function:
Private Sub SeparatePathAndFile(ByRef io_strFolderPath As String, ByRef o_strFileName As String)
Dim strPath() As String
Dim lngIndex As Long
strPath() = Split(io_strFolderPath, "") 'Put the Parts of our path into an array
lngIndex = UBound(strPath)
o_strFileName = strPath(lngIndex) 'Get the File Name from our array
strPath(lngIndex) = "" 'Remove the File Name from our array
io_strFolderPath = Join(strPath, "") 'Rebuild our path from our array
End Sub
You pass the first parameter with the full path of the file and it will be set to the folder's path while the second parameter will be set to the file's name.
answered Dec 4 '12 at 17:15
dnLL
1,949113871
1,949113871
add a comment |
add a comment |
up vote
3
down vote
To get the file name in an excel macro is:
filname = Mid(spth, InStrRev(spth, "", Len(spth)) + 1, Len(spth))
MsgBox Mid(filname, 1, InStr(filname, ".") - 1)
add a comment |
up vote
3
down vote
To get the file name in an excel macro is:
filname = Mid(spth, InStrRev(spth, "", Len(spth)) + 1, Len(spth))
MsgBox Mid(filname, 1, InStr(filname, ".") - 1)
add a comment |
up vote
3
down vote
up vote
3
down vote
To get the file name in an excel macro is:
filname = Mid(spth, InStrRev(spth, "", Len(spth)) + 1, Len(spth))
MsgBox Mid(filname, 1, InStr(filname, ".") - 1)
To get the file name in an excel macro is:
filname = Mid(spth, InStrRev(spth, "", Len(spth)) + 1, Len(spth))
MsgBox Mid(filname, 1, InStr(filname, ".") - 1)
edited Sep 26 '12 at 11:26
Florent
10.7k74153
10.7k74153
answered Sep 19 '12 at 14:17
niki
311
311
add a comment |
add a comment |
up vote
3
down vote
I can't believe how overcomplicated some of these answers are... (no offence!)
Here's a single-line function that will get the job done:
Function getFName(pf)As String:getFName=Mid(pf,InStrRev(pf,"")+1):End Function
Function getPath(pf)As String:getPath=Left(pf,InStrRev(pf,"")):End Function
Examples:
add a comment |
up vote
3
down vote
I can't believe how overcomplicated some of these answers are... (no offence!)
Here's a single-line function that will get the job done:
Function getFName(pf)As String:getFName=Mid(pf,InStrRev(pf,"")+1):End Function
Function getPath(pf)As String:getPath=Left(pf,InStrRev(pf,"")):End Function
Examples:
add a comment |
up vote
3
down vote
up vote
3
down vote
I can't believe how overcomplicated some of these answers are... (no offence!)
Here's a single-line function that will get the job done:
Function getFName(pf)As String:getFName=Mid(pf,InStrRev(pf,"")+1):End Function
Function getPath(pf)As String:getPath=Left(pf,InStrRev(pf,"")):End Function
Examples:
I can't believe how overcomplicated some of these answers are... (no offence!)
Here's a single-line function that will get the job done:
Function getFName(pf)As String:getFName=Mid(pf,InStrRev(pf,"")+1):End Function
Function getPath(pf)As String:getPath=Left(pf,InStrRev(pf,"")):End Function
Examples:
answered Apr 25 at 4:40
ashleedawg
12.5k41848
12.5k41848
add a comment |
add a comment |
up vote
2
down vote
Here's a simple VBA solution I wrote that works with Windows, Unix, Mac, and URL paths.
sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)
sFolderName = Left(sPath, Len(sPath) - Len(sFileName))
You can test the output using this code:
'Visual Basic for Applications
http = "https://www.server.com/docs/Letter.txt"
unix = "/home/user/docs/Letter.txt"
dos = "C:userdocsLetter.txt"
win = "\Server01userdocsLetter.txt"
blank = ""
sPath = unix
sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)
sFolderName = Left(sPath, Len(sPath) - Len(sFileName))
Debug.print "Folder: " & sFolderName & " File: " & sFileName
Also see: Wikipedia - Path (computing)
add a comment |
up vote
2
down vote
Here's a simple VBA solution I wrote that works with Windows, Unix, Mac, and URL paths.
sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)
sFolderName = Left(sPath, Len(sPath) - Len(sFileName))
You can test the output using this code:
'Visual Basic for Applications
http = "https://www.server.com/docs/Letter.txt"
unix = "/home/user/docs/Letter.txt"
dos = "C:userdocsLetter.txt"
win = "\Server01userdocsLetter.txt"
blank = ""
sPath = unix
sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)
sFolderName = Left(sPath, Len(sPath) - Len(sFileName))
Debug.print "Folder: " & sFolderName & " File: " & sFileName
Also see: Wikipedia - Path (computing)
add a comment |
up vote
2
down vote
up vote
2
down vote
Here's a simple VBA solution I wrote that works with Windows, Unix, Mac, and URL paths.
sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)
sFolderName = Left(sPath, Len(sPath) - Len(sFileName))
You can test the output using this code:
'Visual Basic for Applications
http = "https://www.server.com/docs/Letter.txt"
unix = "/home/user/docs/Letter.txt"
dos = "C:userdocsLetter.txt"
win = "\Server01userdocsLetter.txt"
blank = ""
sPath = unix
sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)
sFolderName = Left(sPath, Len(sPath) - Len(sFileName))
Debug.print "Folder: " & sFolderName & " File: " & sFileName
Also see: Wikipedia - Path (computing)
Here's a simple VBA solution I wrote that works with Windows, Unix, Mac, and URL paths.
sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)
sFolderName = Left(sPath, Len(sPath) - Len(sFileName))
You can test the output using this code:
'Visual Basic for Applications
http = "https://www.server.com/docs/Letter.txt"
unix = "/home/user/docs/Letter.txt"
dos = "C:userdocsLetter.txt"
win = "\Server01userdocsLetter.txt"
blank = ""
sPath = unix
sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)
sFolderName = Left(sPath, Len(sPath) - Len(sFileName))
Debug.print "Folder: " & sFolderName & " File: " & sFileName
Also see: Wikipedia - Path (computing)
answered Oct 13 '13 at 16:58
Roberto
2,75611218
2,75611218
add a comment |
add a comment |
up vote
2
down vote
The simplest approach if you are sure the file physically exists on the disk:
Dim fileName, filePath As String
filePath = "C:Documentsmyfile.pdf"
fileName = Dir(filePath)
If you are not sure about existence of file or just want to extract filename from a given path then, simplest approach is:
fileName = Mid(filePath, InStrRev(filePath, "") + 1)
add a comment |
up vote
2
down vote
The simplest approach if you are sure the file physically exists on the disk:
Dim fileName, filePath As String
filePath = "C:Documentsmyfile.pdf"
fileName = Dir(filePath)
If you are not sure about existence of file or just want to extract filename from a given path then, simplest approach is:
fileName = Mid(filePath, InStrRev(filePath, "") + 1)
add a comment |
up vote
2
down vote
up vote
2
down vote
The simplest approach if you are sure the file physically exists on the disk:
Dim fileName, filePath As String
filePath = "C:Documentsmyfile.pdf"
fileName = Dir(filePath)
If you are not sure about existence of file or just want to extract filename from a given path then, simplest approach is:
fileName = Mid(filePath, InStrRev(filePath, "") + 1)
The simplest approach if you are sure the file physically exists on the disk:
Dim fileName, filePath As String
filePath = "C:Documentsmyfile.pdf"
fileName = Dir(filePath)
If you are not sure about existence of file or just want to extract filename from a given path then, simplest approach is:
fileName = Mid(filePath, InStrRev(filePath, "") + 1)
answered Mar 23 '17 at 5:46
ePandit
1,37811311
1,37811311
add a comment |
add a comment |
up vote
1
down vote
Here's an alternative 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))))
add a comment |
up vote
1
down vote
Here's an alternative 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))))
add a comment |
up vote
1
down vote
up vote
1
down vote
Here's an alternative 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))))
Here's an alternative 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))))
edited Mar 4 '14 at 20:39
answered Aug 23 '13 at 14:32
live-love
15.5k87971
15.5k87971
add a comment |
add a comment |
up vote
0
down vote
I needed the path, not the filename.
So to extract the file path in code:
JustPath = Left(sFileP, Len(sFileP) - Len(Split(sFileP, "")(UBound(Split(sFileP, "")))))
add a comment |
up vote
0
down vote
I needed the path, not the filename.
So to extract the file path in code:
JustPath = Left(sFileP, Len(sFileP) - Len(Split(sFileP, "")(UBound(Split(sFileP, "")))))
add a comment |
up vote
0
down vote
up vote
0
down vote
I needed the path, not the filename.
So to extract the file path in code:
JustPath = Left(sFileP, Len(sFileP) - Len(Split(sFileP, "")(UBound(Split(sFileP, "")))))
I needed the path, not the filename.
So to extract the file path in code:
JustPath = Left(sFileP, Len(sFileP) - Len(Split(sFileP, "")(UBound(Split(sFileP, "")))))
edited Oct 3 '13 at 18:38
Darwind
5,77933443
5,77933443
answered Oct 3 '13 at 18:08
Doug
1
1
add a comment |
add a comment |
up vote
0
down vote
This gleaned from Twiggy @ http://archive.atomicmpc.com.au and other places:
'since the file name and path were used several times in code
'variables were made public
Public FName As Variant, Filename As String, Path As String
Sub xxx()
...
If Not GetFileName = 1 Then Exit Sub '
...
End Sub
Private Function GetFileName()
GetFileName = 0 'used for error handling at call point in case user cancels
FName = Application.GetOpenFilename("Ramp log file (*.txt), *.txt")
If Not VarType(FName) = vbBoolean Then GetFileName = 1 'to assure selection was made
Filename = Split(FName, "")(UBound(Split(FName, ""))) 'results in file name
Path = Left(FName, InStrRev(FName, "")) 'results in path
End Function
add a comment |
up vote
0
down vote
This gleaned from Twiggy @ http://archive.atomicmpc.com.au and other places:
'since the file name and path were used several times in code
'variables were made public
Public FName As Variant, Filename As String, Path As String
Sub xxx()
...
If Not GetFileName = 1 Then Exit Sub '
...
End Sub
Private Function GetFileName()
GetFileName = 0 'used for error handling at call point in case user cancels
FName = Application.GetOpenFilename("Ramp log file (*.txt), *.txt")
If Not VarType(FName) = vbBoolean Then GetFileName = 1 'to assure selection was made
Filename = Split(FName, "")(UBound(Split(FName, ""))) 'results in file name
Path = Left(FName, InStrRev(FName, "")) 'results in path
End Function
add a comment |
up vote
0
down vote
up vote
0
down vote
This gleaned from Twiggy @ http://archive.atomicmpc.com.au and other places:
'since the file name and path were used several times in code
'variables were made public
Public FName As Variant, Filename As String, Path As String
Sub xxx()
...
If Not GetFileName = 1 Then Exit Sub '
...
End Sub
Private Function GetFileName()
GetFileName = 0 'used for error handling at call point in case user cancels
FName = Application.GetOpenFilename("Ramp log file (*.txt), *.txt")
If Not VarType(FName) = vbBoolean Then GetFileName = 1 'to assure selection was made
Filename = Split(FName, "")(UBound(Split(FName, ""))) 'results in file name
Path = Left(FName, InStrRev(FName, "")) 'results in path
End Function
This gleaned from Twiggy @ http://archive.atomicmpc.com.au and other places:
'since the file name and path were used several times in code
'variables were made public
Public FName As Variant, Filename As String, Path As String
Sub xxx()
...
If Not GetFileName = 1 Then Exit Sub '
...
End Sub
Private Function GetFileName()
GetFileName = 0 'used for error handling at call point in case user cancels
FName = Application.GetOpenFilename("Ramp log file (*.txt), *.txt")
If Not VarType(FName) = vbBoolean Then GetFileName = 1 'to assure selection was made
Filename = Split(FName, "")(UBound(Split(FName, ""))) 'results in file name
Path = Left(FName, InStrRev(FName, "")) 'results in path
End Function
edited Oct 3 '14 at 6:47
answered Oct 3 '14 at 6:41
Dan
63
63
add a comment |
add a comment |
up vote
0
down vote
Function file_name_only(file_path As String) As String
Dim temp As Variant
temp = Split(file_path, Application.PathSeparator)
file_name_only = temp(UBound(temp))
End Function
- here you give your file name as input of the function
- the split function of VBA splits the path in different portion by using "" as path separator & stores them in an array named "temp"
- the UBound() finds the max item number of array and finally assigns the result to "file_name_only" function
Hope this will be helpful.
add a comment |
up vote
0
down vote
Function file_name_only(file_path As String) As String
Dim temp As Variant
temp = Split(file_path, Application.PathSeparator)
file_name_only = temp(UBound(temp))
End Function
- here you give your file name as input of the function
- the split function of VBA splits the path in different portion by using "" as path separator & stores them in an array named "temp"
- the UBound() finds the max item number of array and finally assigns the result to "file_name_only" function
Hope this will be helpful.
add a comment |
up vote
0
down vote
up vote
0
down vote
Function file_name_only(file_path As String) As String
Dim temp As Variant
temp = Split(file_path, Application.PathSeparator)
file_name_only = temp(UBound(temp))
End Function
- here you give your file name as input of the function
- the split function of VBA splits the path in different portion by using "" as path separator & stores them in an array named "temp"
- the UBound() finds the max item number of array and finally assigns the result to "file_name_only" function
Hope this will be helpful.
Function file_name_only(file_path As String) As String
Dim temp As Variant
temp = Split(file_path, Application.PathSeparator)
file_name_only = temp(UBound(temp))
End Function
- here you give your file name as input of the function
- the split function of VBA splits the path in different portion by using "" as path separator & stores them in an array named "temp"
- the UBound() finds the max item number of array and finally assigns the result to "file_name_only" function
Hope this will be helpful.
answered Nov 11 at 10:42
mishu36
11
11
add a comment |
add a comment |
up vote
-1
down vote
Dim nme As String = My.Computer.FileSystem.GetFileInfo(pathFicheiro).Name
Dim dirc As String = My.Computer.FileSystem.GetFileInfo(nomeFicheiro).Directory
Although your answer may work for the question, could you please add some explanation of what is doing?
– Ivan
Aug 25 '15 at 12:00
This is better solution. It extracs filename and directory from given path pathFicheiro. There is no need for nomeFicheiro as you could just use pathFicheiro. pathFicheiro = FILENAME variable
– user1054844
Nov 15 '16 at 9:25
Sorry but unless I'm missing something, this is .net, so it doesn't answer the vba question.
– ashleedawg
Apr 25 at 4:44
add a comment |
up vote
-1
down vote
Dim nme As String = My.Computer.FileSystem.GetFileInfo(pathFicheiro).Name
Dim dirc As String = My.Computer.FileSystem.GetFileInfo(nomeFicheiro).Directory
Although your answer may work for the question, could you please add some explanation of what is doing?
– Ivan
Aug 25 '15 at 12:00
This is better solution. It extracs filename and directory from given path pathFicheiro. There is no need for nomeFicheiro as you could just use pathFicheiro. pathFicheiro = FILENAME variable
– user1054844
Nov 15 '16 at 9:25
Sorry but unless I'm missing something, this is .net, so it doesn't answer the vba question.
– ashleedawg
Apr 25 at 4:44
add a comment |
up vote
-1
down vote
up vote
-1
down vote
Dim nme As String = My.Computer.FileSystem.GetFileInfo(pathFicheiro).Name
Dim dirc As String = My.Computer.FileSystem.GetFileInfo(nomeFicheiro).Directory
Dim nme As String = My.Computer.FileSystem.GetFileInfo(pathFicheiro).Name
Dim dirc As String = My.Computer.FileSystem.GetFileInfo(nomeFicheiro).Directory
answered Aug 25 '15 at 9:36
Paulos02
12614
12614
Although your answer may work for the question, could you please add some explanation of what is doing?
– Ivan
Aug 25 '15 at 12:00
This is better solution. It extracs filename and directory from given path pathFicheiro. There is no need for nomeFicheiro as you could just use pathFicheiro. pathFicheiro = FILENAME variable
– user1054844
Nov 15 '16 at 9:25
Sorry but unless I'm missing something, this is .net, so it doesn't answer the vba question.
– ashleedawg
Apr 25 at 4:44
add a comment |
Although your answer may work for the question, could you please add some explanation of what is doing?
– Ivan
Aug 25 '15 at 12:00
This is better solution. It extracs filename and directory from given path pathFicheiro. There is no need for nomeFicheiro as you could just use pathFicheiro. pathFicheiro = FILENAME variable
– user1054844
Nov 15 '16 at 9:25
Sorry but unless I'm missing something, this is .net, so it doesn't answer the vba question.
– ashleedawg
Apr 25 at 4:44
Although your answer may work for the question, could you please add some explanation of what is doing?
– Ivan
Aug 25 '15 at 12:00
Although your answer may work for the question, could you please add some explanation of what is doing?
– Ivan
Aug 25 '15 at 12:00
This is better solution. It extracs filename and directory from given path pathFicheiro. There is no need for nomeFicheiro as you could just use pathFicheiro. pathFicheiro = FILENAME variable
– user1054844
Nov 15 '16 at 9:25
This is better solution. It extracs filename and directory from given path pathFicheiro. There is no need for nomeFicheiro as you could just use pathFicheiro. pathFicheiro = FILENAME variable
– user1054844
Nov 15 '16 at 9:25
Sorry but unless I'm missing something, this is .net, so it doesn't answer the vba question.
– ashleedawg
Apr 25 at 4:44
Sorry but unless I'm missing something, this is .net, so it doesn't answer the vba question.
– ashleedawg
Apr 25 at 4:44
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1743328%2fhow-to-extract-file-name-from-path%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Try using the split function to get the file name from the path: MSDN link
– jonaspp
Nov 16 '09 at 16:44