Search code examples
excelvbatrimsubdirectoryfso

VBA Trim one Object with another Object in string (FSO.Getfolder related) Basically end up with relative path to a file


I am building this index of files in a directory. Column 1 with folder name(s), Column 2 with filename

I have managed to get the actual filename and hyperlinking the filename already. But I have problems listing the path to the file in column 1, using a relative path including its subfolders.

Say I have the following folder: "C:\users\ME\Documents" Inside that folder there are many subfolders.

What I want to achieve is a string that list the path to that actual subfolder. Example:

"C:\users\ME\Documents\Subfolder1\Subfolder2\CharlieSheen.pdf"
Column 1 (A5) = Subfolder1\Subfolder2\
Column 2 (B5) = CharlieSheen.pdf

As I said I have control over column 2.

The script I am using already is

Private Function GetAllFiles(ByVal strpath As String, _
ByVal intRow As Integer, ByRef objFSO As Object) As Integer
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer`
i = intRow - ROW_FIRST + 1

Set objFolder = objFSO.Getfolder(strpath)
For Each objFile In objFolder.Files
'print file path
    Cells(i + ROW_FIRST - 1, 1) = objFolder.Name

i = i + 1
    Next objFile
    GetAllFiles = i + ROW_FIRST - 1
End Function

I figured out that changing
Cells(i + ROW_FIRST - 1, 1) = objFolder.Name

into Cells(i + ROW_FIRST - 1, 1) = objFSO.Getfolder(".") returned exactly what I wanted to remove from the first string!

So I basically want to write a script that says:

Cells(i + ROW_FIRST - 1, 1) = objFolder.Name - objFSO.Getfolder(".")

But I need help since that command obviously doesn't work.

There might be a totally different approach to this, but since my macro already have a lot of code, using Trim or Replace or similar would be the easiest?

Edit: There's also a function in my script named "GetAllFolders". Maybe I can call on that in some way to implement the string I want?

Private Sub GetAllFolders(ByVal strFolder As String, _
    ByRef objFSO As Object, ByRef intRow As Integer)
Dim objFolder As Object
Dim objSubFolder As Object

'Get the folder object
Set objFolder = objFSO.GetFolder(strFolder)
'loops through each file in the directory and
'prints their names and path
For Each objSubFolder In objFolder.subfolders
    intRow = GetAllFiles(objSubFolder.Path, _
        intRow, objFSO)
    'recursive call to to itsself
    Call GetAllFolders(objSubFolder.Path, _
        objFSO, intRow)
Next objSubFolder
End Sub

Solution

  • What about

    Cells(i + ROW_FIRST - 1, 1) = Replace$(objFolder.Name, CStr(objFSO.Getfolder(".")), vbNullString)