PDA

View Full Version : easy path splitting question



TheAntiGates
11-14-2007, 04:05 PM
I would like to parse the path from a nonexistent filename in a string, such as "c:\MyDir\UN-FILE.XLS" giving "c:\MyDir"

GetFile requires a file to exist. Since I thus would need to create a temporary file and afterwards delete it (phew), and I feel it's beneath my dignity to write a colon and backslash parser (pee-yeww)... is there some other "official" avenue to split out drive and/or path and/or filename?

Access 03 VBA

[EDIT:] (Later) Hearing no response so far - out it comes. Will this do?Function GetPathName(ByVal Path As String) As String
Dim sParts() As String, i As Long
sParts = Split(Path, "\")
i = InStrRev(Path, sParts(UBound(sParts)))
GetPathName = Left(sParts, i - 1)
End Function

alimcpill
11-15-2007, 02:17 AM
FileSystemObject has GetParentFolderName(Path As String) As String which would give you what you need if you have scripting runtime

TheAntiGates
11-16-2007, 06:03 PM
Thanks for the response, but I had to stick with the code.

1. My code above seems fine with one correction. I'm disappointed no one was even interested enough to try it and notice that. :motz2: The correction is to change
Left(sParts, i - 1)
to
Left(Path, i - 1)

2. With Microsoft Scripting Runtime checked in My Access 03 references, attempting
?GetParentFolderName("c:\foobar.")
yields "Compile error: Sub or Function not defined"

3. For the benefit of anyone wanting to ensure that the scripting reference is established, it is set by the code line
Application.References.AddFromGuid "{420B2830-E718-11CF-893D-00A0C9054228}", 0, 0
which is good On Error content, followed by a simple Resume

Tommy
11-17-2007, 08:18 AM
Try This, of course I am not checking for an empty Path, I am assuming a valid path is sent.

Function GetPathName(ByVal Path As String) As String
GetPathName = Left(Path, InStrRev(Path, "\") - 1)
End Function

Norie
11-17-2007, 08:34 AM
Gates

I'm glad you seem to have a solution but I would really suggest you don't use Path as a name for the parameter/variable.

And also your solution will include the last "\", which you didn't seem to want in your original post.


Function GetPathName(ByVal MyPath As String) As String
Dim sParts() As String
sParts = Split(MyPath, "\")
GetPathName = sParts(0) & "\" & sParts(1)
End Function

TheAntiGates
11-17-2007, 10:35 AM
Nice job, Tommy. Thanks. The error checking is also important, whether done there or preceding the call.

Good point about the variable name, Norie - I'm busted. But otherwise I'll stick with Tommy's code, as it's more general.