Split Directory\filename into two variables

B

bill_campbell

In my macro a user selects a filename using:

With Dialogs(wdDialogFileOpen)
If .Display Then
strSourceFile = WordBasic.FilenameInfo$(.Name, 1)
End If
End With

I want to split strSourceFile into a directory part, and a filename
part. I've done this before by starting at the left most point of a
string, then backing up one character untill a backslash is found, but
I think there is probably something all ready built into VBA to do this.
 
J

JBNewsGroup

Hi Bill,

Look at the functions "Instr" (left to right scan) and "InstrRev" (right to
left scan). For Instance:

J = InstrRev (strSourceFile,"\",-1,vbTextCompare)
If (J <= 0) then
-- no backslash, do something --
Else
DirectoryPart = Left$(strSourceFile , J-1)
FileNamePart = Mid$(strSourceFile ,J+1)
End If

In the Lewft$ function change J-1 to J if you want the backslash included.
Instead of Mid$ you could also use Right$.

Jerry Bodoff
 
B

bill_campbell

I found (mostly by luck) that by switching the number following .Name
to 5 and 3, I could pull the information I needed.
 
B

bill_campbell

I found (mostly by luck) that by switching the number following .Name
to 5 and 3, I could pull the information I needed.
 
P

Pete Bennett

It's even easier to use FileSystemObject (you'll need to add in a reference
to Microsoft Scripting Runtime to get it to work)

Dim fso as FileSystemObject

Debug.Print fso.GetParentFolderName("c:\temp\harry.xml")
Debug.Print fso.GetFileName("c:\temp\harry.xml")

Will give you the information you need. Play with it and you'll see it's a
pretty good little file handler. It even supplies read and write functions
as well.
 
J

JBNewsGroup

Hi Pete,

I have been using the FileSystemObject for a while and I did not realize
that I could do I/O with it. I am going to check it out. It is like a
friend says, "read the book when you need it".

Thanks for the tip.

Jerry Bodoff
 

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