Creating an index of a directory using macros

ChristianBacklund

New Member
Joined
Jul 10, 2002
Messages
44
I would like to create a macro which will copy the names of the files and folders of a chosen directory into a spreadsheet, effectively creating an index. I don't know how to go about this or even if it is possible. I'm trying to avoid having to do it manually as the directory in question spans 1500 folders... Any help would be greatly appreciated
 
I knew your second request was coming, because I would not release something like this to all-and-sundry. :smile: If you want to do this yourself, check out Inputbox, GetSaveAsFileName and GetOpenFileName

Your first one took me by surprise since you said that you wanted "an inventory of a drive!" I imagine one could add expand the if clause that checks for "." and ".."
 
Upvote 0

Excel Facts

What did Pito Salas invent?
Pito Salas, working for Lotus, popularized what would become to be pivot tables. It was released as Lotus Improv in 1989.
I already tried adding 'And aFileName = ".xls"' after 'If aFileName = "." Or aFileName = ".."' I can't seem to figure out how to get it to single out the filenames I want. Sorry to keep bugging you, but can you help? And what did you mean, you don't release it to all-and-sundry? Why is that?
Also, I can't see how any of the functions you showed me can help specify the directory! Sorry, but I'm new to VB (only been at it 3 days!)
 
Upvote 0
By "all and sundry" I meant non-programmers.

If you want a completely functional add-in, check out the Directory List page of my web site. I completed the program a little while ago.
 
Upvote 0
Try this set of utilities, from a module. See notes on changes you can make, like which file types and what drive, path or folders. JSW

Sub FilesInDirectory()
Dim lngCellCounter As Long
'Search current directory for all files.
'Run from module.
'Change FileType to the type you want! Like: msoFileTypeAllFiles.
'Change LookIn to your drive & path. Like "C:/"
Application.ScreenUpdating = False
With Application.FileSearch
.NewSearch
.FileType = msoFileTypeExcelWorkbooks
.LookIn = CurDir()
.SearchSubFolders = False
If .Execute() > 0 Then

MsgBox "There were " & .FoundFiles.Count & " file(s) found."

For lngCellCounter = 1 To .FoundFiles.Count
Cells(lngCellCounter, 1) = .FoundFiles(lngCellCounter)
Sheets("Sheet1").Select
Next lngCellCounter

Range("A1").Select
Selection.EntireRow.Insert
Range("AA2").Select
Selection.Copy
Range("A1").Select
ActiveSheet.Paste
Else

MsgBox "No Excel WorkBooks found!"
End If

End With
Application.ScreenUpdating = True
End Sub


Sub GetAllFiles()
Dim lngCellCounter As Long
'Search all subdirectories of the current directory or other.

Application.ScreenUpdating = False
'Change FileType to the type you want! Like: msoFileTypeAllFiles.
'Change LookIn to your drive & path. Like "C:/"
With Application.FileSearch
.NewSearch
.FileType = msoFileTypeExcelWorkbooks
.LookIn = CurDir()
.SearchSubFolders = True
If .Execute() > 0 Then

MsgBox "There were " & .FoundFiles.Count & " file(s) found."

For lngCellCounter = 1 To .FoundFiles.Count
Cells(lngCellCounter, 1) = .FoundFiles(lngCellCounter)
Sheets("Sheet1").Select
Next lngCellCounter

Range("A1").Select
Selection.EntireRow.Insert
Range("AA2").Select
Selection.Copy
Range("A1").Select
ActiveSheet.Paste
Else

MsgBox "No Excel WorkBooks found!"

End If
End With
Application.ScreenUpdating = True
End Sub

Sub Look_In_x()
Dim lngCellCounter As Long
Dim Message, Title, Default, MyDir
'Search current directory for all files.
'Change FileType to the type you want! Like: msoFileTypeAllFiles.
Application.ScreenUpdating = False
Message = "Enter the directory to search?" & Chr(13) & Chr(13) & "(Drive:\\Directory\\SubDirectory)" ' Set prompt.
Title = "Enter: Drive and Path!" ' Set title.
Default = "C:" ' Set default drive & path.
' Display message, title, and default value.
On Error GoTo myErr

MyDir = InputBox(Message, Title, Default)

With Application.FileSearch
.NewSearch
.FileType = msoFileTypeExcelWorkbooks
.LookIn = MyDir
.SearchSubFolders = True
If .Execute() > 0 Then

MsgBox "There were " & .FoundFiles.Count & " file(s) found."

For lngCellCounter = 1 To .FoundFiles.Count
Cells(lngCellCounter, 1) = .FoundFiles(lngCellCounter)
Sheets("Sheet1").Select
Next lngCellCounter

Range("A1").Select
Selection.EntireRow.Insert
Range("AA2").Select
Selection.Copy
Range("A1").Select
ActiveSheet.Paste
Else

MsgBox "No Excel WorkBooks found!"
End If

End With
Application.ScreenUpdating = True
End
myErr:

MsgBox "No Excel WorkBooks found!"

End Sub

Sub Delete_Data()
'Delete the current screen print of file data.

Application.ScreenUpdating = False
Columns("A:A").Select
Selection.ClearContents
Range("A1").Select
Selection.EntireRow.Delete
Range("C1").Select
Application.ScreenUpdating = True
End Sub
 
Upvote 0
Tushar, I downloaded your Directory Listing Add-In, and loaded it into Excel, got the menu item et al, and when I tried to run it, I got an error message saying "The macro 'directory.xla!startADir' cannot be found". What do I need to do?
Thanks!
 
Upvote 0
I'm having trouble making things work. What I'd ideally like to do is to be able to preserve the code Tushar gave me before(found in the second-last post on Page 1 of this stream) and simply modify it so that it can pick out specific file types (namely .pdf, .vsd, .doc, . xls) and also to bring up a window which asks the user which directory they wish to search. If anyone could show me explicitly which changes to make, it would make it much easier for me. Many thanks.
 
Upvote 0
On 2002-07-15 01:29, ChristianBacklund wrote:
I'm having trouble making things work. What I'd ideally like to do is to be able to preserve the code Tushar gave me before(found in the second-last post on Page 1 of this stream) and simply modify it so that it can pick out specific file types (namely .pdf, .vsd, .doc, . xls) and also to bring up a window which asks the user which directory they wish to search. If anyone could show me explicitly which changes to make, it would make it much easier for me. Many thanks.
The reason I wrote the add-in is that creating -- especially validating -- an userform is not trivial.

I will check and see why the add-in doesn't work. When I tested it, everything worked fine.

As far as tracking specific file types goes, you can try the foll. untested code.

Code:
Option Explicit
    Function GoodFileExtension(fName As String) As Boolean
        If Len(fName) <= 4 Then Exit Function
        Select Case Right(fName, 4)
        Case ".xls", ".doc", ".pdf"
            GoodFileExtension = True
        Case Else
            End Select
        End Function
Sub doADirectory(whatDir As String, OutputCell As Range)
    Dim aFileName As String, FullName As String, i As Integer
    ReDim FolderList(1 To 1) As String
    
    aFileName = Dir(whatDir, &H1F)
        'cheating a bit here; look up DIR in XL VBE help for 2nd argument
    OutputCell.Value = whatDir
    Set OutputCell = OutputCell.Offset(1, 1)
    Do While aFileName <> ""
        If aFileName = "." Or aFileName = ".." _
            Or Not GoodFileExtension(aFileName) Then
        Else
            FullName = whatDir & aFileName
            If (GetAttr(FullName) _
                And vbDirectory) = vbDirectory Then
                ReDim Preserve FolderList(LBound(FolderList) To UBound(FolderList) + 1)
                FolderList(UBound(FolderList)) = aFileName
            Else
                OutputCell.Value = aFileName
                Set OutputCell = OutputCell.Offset(1, 0)
                End If
            End If
        aFileName = Dir
        Loop
    For i = LBound(FolderList) + 1 To UBound(FolderList)
        doADirectory whatDir & FolderList(i) & Application.PathSeparator, OutputCell
        Set OutputCell = OutputCell.Offset(0, -1)
        Next i
    End Sub
Sub startADir()
    'doADirectory "c:my documents", Range("a1")
    doADirectory Range("dirName"), Range(Range("OutputStartCell"))
    'The cell named dirName should have the full path of the directory _
     including the trailing  _
     The cell named OutputStartCell should have the address of where _
     the output should start, such as A1.
    End Sub
 
Upvote 0
That works great, it limits the search beautifully. There is one hitch though. It has now lost the ability to work into subfolders, and only indexes the immediate folder. This isn't entirely bad, but what would be great would be to have that as an optional functionality. So, if there was a checkbox which when ticked would cause the program to index subfolders as well... I just need to know why the program stopped indexing subfolders!!

PS. What do I need to add in to make the macro return a msgbox which states when the folder doesn't exist or is empty??
This message was edited by ChristianBacklund on 2002-07-15 07:03
 
Upvote 0
Three things, and I guarantee that you -- and others who do the same thing -- will take offence at #3.

(1) I downloaded the add-in from my web site on a second machine and it worked fine. So, I don't know what the problem was on your computer.

(2) Replace the complete IF statement with:
Code:
        If aFileName = "." Or aFileName = ".." Then
        Else
            FullName = whatDir & aFileName
            If (GetAttr(FullName) _
                And vbDirectory) = vbDirectory Then
                ReDim Preserve FolderList(LBound(FolderList) To UBound(FolderList) + 1)
                FolderList(UBound(FolderList)) = aFileName
            ElseIf GoodFileExtension(aFileName) Then
                OutputCell.Value = aFileName
                Set OutputCell = OutputCell.Offset(1, 0)
                End If
            End If

(3) This is my last post on the subject. I have now spent over 8 hours helping you out.

This forum and others I participate in are supposed to *help* people with *specific* problems, not provide them with free complete solutions.

If you want a customized solution to a problem, you should consider hiring a consultant. Instead you, and, yes, I know you are not alone, ask for 'one more thing' after 'one more thing' after 'one more thing.'

No more. No more pro bono consulting. At least not from me.
 
Upvote 0

Forum statistics

Threads
1,223,923
Messages
6,175,398
Members
452,640
Latest member
steveridge

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top