Show last folder not full path

J

Joe

Hi all -

New to vba and could use a little help.

I'm prompting the user to select a folder using:

With Dialogs(wdDialogCopyFile)
If .Show <> 0 Then
myFolder = .directory

Later on I'd like to be able to display only the name of the last folder in the path. If I use msgbox myFolder it displays the entire path. Can anyone suggest a method for accomplishing this.

Thanks in advance.
Joe
 
J

Jay Freedman

Hi, Joe,

You have to figure out where the last backslash is, and take the
substring to the right of it. Allowing for the fact that the string
starts with quotes around it, and usually a backslash at the end of
the string inside the quotes, you have to do something like this:

Sub Folder()
Dim myFolder As String
Dim myPath As String
Dim nSlash As Long

With Dialogs(wdDialogCopyFile)
If .Display <> 0 Then
myPath = .directory
End If
End With

' remove the quotes
myPath = Replace(myPath, """", "")

If Len(myPath) <= 3 Then
' "C:\" or similar, or empty
myFolder = myPath
Else
' if last character is a backslash,
' remove it
If Right(myPath, 1) = "\" Then
myPath = Left(myPath, Len(myPath) - 1)
End If

' find the last remaining backslash
nSlash = InStrRev(myPath, "\")

' extract the substring that follows it
If nSlash > 0 Then
myFolder = Right(myPath, Len(myPath) - nSlash)
End If
End If

MsgBox myFolder
End Sub

Some things involving manipulation of file paths can be done most
easily with the WordBasic.FilenameInfo$ function (see
http://www.mvps.org/word/FAQs/MacrosVBA/WordBasicCommands.htm), but
this isn't one of them.
 
J

Joe

Thanks a lot Jay. That's exactly what I needed.

I follow all the steps except for one part regarding removing the quotes.
myPath = Replace(myPath, """","")
If the original path is "C:\SomeFolder", which appears with two quotes, why search for a substring of four quotes?

Thanks again.
Joe
 
J

Jay Freedman

Hi, Joe,

It's just one of those "programming things". Whoever designed the
Basic language had a problem: quotes are used as delimiters for
strings in assignment statements, but how do you then represent a
string that consists of a quote character? Also consider how the
interpreter decides where to stop looking for the end of the string
when confronted with an expression like
""",""
Does it end at the second quote, the third, or the fourth? Is the
comma part of the string or does it separate two strings? The decision
was, more or less arbitrarily, that a string consisting of one quote
character is represented as four consecutive quotes. The Replace
function as written replaces each quote character with nothing.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top