2

I am stuck with an issue. I've done my research and found out that I can use InSTR function to search for a specific character in a string.

What I am trying to do is get a file name extracted from a file path.

Currently I have

  InStr(StrFrom(pName), "\")

The issue here is, it returns the first occurrence of slash, where as I want to get the last occurrence of the slash (so that I can use a 'right' function wrapped around the above code to capture the file name)

Any help is appreciated on how to get the last slash in a string!

Thanks!

1

4 Answers 4

9

Instr looks from the start of the text string, InstrRev starts looking from the other end.

Public Function FileNameOnly(ByVal FileNameAndPath As String) As String

    FileNameOnly = Mid(FileNameAndPath, InStrRev(FileNameAndPath, "\") + 1, Len(FileNameAndPath))

End Function
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks all - I've used a combination about instrRev + above logic to get the name :)
Was going to add MsgBox CreateObject("Scripting.FileSystemObject").GetFileName(CreateObject("Scripting.FileSystemObject").GetAbsolutePathName("<Full Path To File>")) as a one liner - not particularly useful though (calls the FileSystemObject twice). :)
both fine solutions to which I'd add 1) use Application.PathSeparator instead of "\" and give it more generality 2) avoid double FileSystemObject objects With CreateObject "Scripting.FileSystemObject")| FileNameOnly = .GetFileName(.GetAbsolutePathName(FileNameAndPath))| End With -
Application.PathSeparator - that was the command I was trying to remember. Couldn't think of the wording to save my life. :)
3

Consider:

Sub marine()
    Dim s As String, ary
    s = "C:\whatever\sub1\sub2\reallydeep\x.xlsm"
    ary = Split(s, "\")
    MsgBox ary(UBound(ary))
End Sub

enter image description here

Comments

2

Use InStrRev() to find the first occurrence of the slash from the right side of the string.

https://msdn.microsoft.com/en-us/library/t2ekk41a(v=vs.90).aspx

Comments

1

Assuming StrFrom is some user defined function, the following will do what you want:

Dim filename as String
Dim path as String

path = StrFrom(pName)
filename = Mid$(path, InstrRev(path, "\") + 1)

Note that its easier to use Mid$ than Right$, as InstrRev returns the character position from the left of the string. Omitting the final parameter of Mid$, returns the rest of the string from that position.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.