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 have 2 final things to say on this topic.
1) Tushar, thank you for your help, it has been absolutely invaluable. I only just started on my job two weeks ago, as part of my university degree. I've had no experience of VB, but got this 'easy' project dumped on me from the start. I've spent the last week and a half vainly trying to figure it out. Without your help I would have had no chance whatsoever of completing this task, but would have started my year's employment with failure. Instead, your code works wonders, and I have learned a lot about VB from your code.
2) I do not take offense at your third comment, in fact I think it was entirely appropriate. I never meant to ask for 'just one more thing' again and again. Initially I had no idea how hard this was, and I had trouble saying what I was trying to do, which is why I kept asking how to do additional things. I think now if you look back on my first post, you'll find pretty much everything that I subsequently asked. I just didn't realise how much I was asking, having no experience of VB. I thought there was some functionality in VB that did it, I didn't think it would need a 'customised solution'. I apologise for making you feel that I was taking advantage of your generosity, I never meant to do so. I am aware that it happens on boards like this, but had no intention of doing so. Simply, I'm just lost with VB and need all the help I can get. For sharing your Excel wizardry with me and the many who have viewed this topic, I thank you profusely. I'm sorry you spent 8 hours helping me and came out feeling angry about it. I do however, understand why. I will waste no more of your time.
Thank you,
Christian
 
Upvote 0

Excel Facts

When they said...
When they said you are going to "Excel at life", they meant you "will be doing Excel your whole life".
That's a very gracious comeback, especially in the face of my outburst. I'm sorry it was you I took my frustrations out on.

I am happy to help people out, but in the last few days, I seem to have responded to the 'wrong' posts. To me the *perceived* attitude of the a few (some/many?) posters has been "I don't know what I'm doing, XL sucks, VBA sucks, MS sucks, OLH sucks, I don't want to learn, just give me a functioning solution, and I want it for free."

In each case, the original poster has not come out and said, "This is the scope of all that I need done." Instead, the questions seem to come one piece at a time. "I need help with this one little problem." As soon as someone -- myself, or one of the others who has been volunteering time on this board for much longer -- responds, the OP pops back with, "No, but what I really want is..." Or, "Well, I also need this one other little piece..."

I know it is not your problem and, again, I apologize for making you the target of my frustrations.
 
Upvote 0
Tushar, it is as much my problem as it is yours. I am a poster, and as such I need to realise that those people helping me need to know, as you say, the full scope of the issue right from the start. I tried to do that, by stating what I wanted to do in my first post. I also don't want to be one of those people who, as you say, just want a free solution. I'm here trying to learn. However, I do acknowledge that a lot of the time I came back not being able to do it, because I'd spent hours struggling with it, without getting anywhere. From now on I'll try to do it on my own more. The more VB I can learn, the less I'll have to ask.
Don't apologise for your comments, they were fully justified. Also, judging from the amount of people viewing this topic, it was a good place to say it, as you hopefully got through to a lot of people. Well, I have to get back to VB now, have to try and get this finished soon! I have a feeling that every time I manage to overcome the problems I encounter, my manager is going to ask for added functionality, hence more trouble. Isn't life a joy?
Anyway, thanks again Tushar, I appreciate your help immensely, and I apologise again. Maybe next time I need help, whomever is nice enough to give me a hand won't feel that I'm abusing their generosity.
Thanks,
Christian
 
Upvote 0
Hi Christian


Hope this doesn't appear as me 'butting' in.

I can see where Tushar is coming from. It is all to often that we start to help and then only find out later that they never relayed their problem correctly in the first place (not saying that you fit that description).

I guess it would be nice if the askers would be as dedicated to helping themselves as people like Tushar are.

If we start to help and then abandon them, once it becomes clear they do not know what they really want, we often get a bad name. You would be suprised at just how many people expect undivided attention for free. They then do not even bother to type 2 magic words,ie Thank You. At the end of the day that is all we want.
 
Upvote 0
Exactly, why should askers get undivided attention for free, and if not they complain? Tushar has been a veritable gem in helping me, but I didn't actually expect him to come back and help every time, I sometimes asked him specifically because I thought he'd know best (as he gave me the original code). I also tried leaving it open, so that others would take over, so I didn't overload Tushar. All I can say is that I agree with both of you. I'll try to be explicit from the start, and I hope everyone else who reads this takes note! And no, you weren't butting in, more people should say what they think about this topic! (Maybe a good idea for a new post?)
 
Upvote 0
Hi, I just wanted to drop in and add what might be a useable solution for looping through directories...

I'm using this recursive function on one of my projects to look for folders whose names contain a certain date. It works for any amount of sub-directories:

Code:
Private Sub FindOldFiles(myFolder)

    Set SubFolderSet = myFolder.SubFolders
    
    For Each Folder In SubFolderSet
    
        If InStr(1, Folder.Name, LastFolderDate) Then
        
            DeleteList = DeleteList & Folder & vbNewLine
            
        Else
            Call FindOldFiles(Folder)
        
        End If
    Next Folder

End Sub
 
Upvote 0
Hi all,

I've been tasked at work with clearing up our mega sized shared area before we move to a MS Sharepoint system. The task is mammoth and i'm trying to index everything we have. i've toyed with a couple of the macros that i found here and on other sites for indexing files into excel and they work great. The only question i have is this:

Is it possible to include "author" and "owner" of the files in the output list. You can do this in explorer if you select View>Choose Details.

Any ideas?? - It would be sooooo useful to me!
 
Upvote 0
Try this, to list file information from a folder you select from the included Dialog:


Sub Get_Files_With_FSO()
'Standard code module only, like: Module1.
Dim objFSO As Object, objFolder As Object
Dim objFiles As Object, objThisFile As Object
Dim strDirectory$, strMyFolder$, strMyFilePath$
Dim ws As Worksheet
Dim wb As Workbook
Dim lngRowInfo&

Application.DisplayAlerts = False
On Error GoTo myError

'Display Folder Shell, for you to select your Folder, Option Switches:
'BrowseForFolder(hwnd,Title,ulFlags,RootFolder)= hwnd==> "handle to the parent window of the dialog box.
'0 Zero is the current window"

'BrowseForFolder(hwnd,Title,ulFlags,RootFolder)= Title==> "Custom Title for Dialog Box"

'BrowseForFolder(hwnd,Title,ulFlags,RootFolder)= ulFlags==> "ulFlags as listed below!"
'ulFlags: 0 Zero(Default No Restriction [Best to Use!]) or a combination of the following values.
'BIF_BROWSEFORCOMPUTER(Only computers anything else, the OK button is grayed.)
'BIF_BROWSEFORPRINTER(Only printersanything else, the OK button is grayed. Note:
'In Windows XP, use an XP-style dialog, setting the root to Printers and Faxes folder (CSIDL_PRINTERS).)
'BIF_BROWSEINCLUDEFILES(Version 4.71. The browse dialog box will display files as well as folders.)
'BIF_DONTGOBELOWDOMAIN(Do not include network folders below domain level in box's tree view control.)
'BIF_NOTRANSLATETARGETS(Version 6.0. If selected item is: shortcut, return the PIDL of the shortcut itself
'rather than its target.)
'BIF_RETURNFSANCESTORS(Only return file system ancestors: The subfolder that is beneath the root folder
'in the namespace hierarchy. If the ancestor is not part of the file system, the OK button is grayed.)
'BIF_RETURNONLYFSDIRS(Only file system directories, if not part of the file system, the OK button is grayed.)

'BrowseForFolder(hwnd,Title,ulFlags,RootFolder)= RootFolder==> "Root Folder Option, as listed below!"
'Current-Folder==>Left(CurDir, 3), 17=AllFilesDeskTop(MyComputer), 0=Root(DeskTop), 28=ApplicationData,
'8=Recent, 23=Common(Programs), 2=Top(Programs), 38=All(Programs), 3=Controls, 39=Pictures,
'5=MyDocuments, 4=Printers&Faxs, 27=PrintHood, 32=TempInternet, 20=Fonts, 34=InternetHistory,
'11=StartMenu, 7=StartUp(Only), 21=Templates, 36=Windows , 39=MyPictures, 33=cookies,
'16=DeskTop, 6=Favorites,18=Network, 19=NetHood, 5=Personal(MyDocuments), 40=UserProfile,
'9=SendToMenuItems, 37=System.


Set objFolder = CreateObject("Shell.Application"). _
BrowseForFolder(0, "Please Select a Folder!", 0, 17)

'Condition Folder for RootFolder or SubFolder Path!
If Not objFolder Is Nothing Then
If Len(objFolder.Items.Item.Path) > 3 Then
strMyFolder = objFolder.Items.Item.Path & Application.PathSeparator
Else

strMyFolder = objFolder.Items.Item.Path
End If
End If

'Hold your selected Folder for use!
ChDir strMyFolder
strMyFilePath = strMyFolder

'Build Folder's Files list!
Set objFSO = CreateObject("scripting.filesystemobject")
Set objFolder = objFSO.GetFolder(strMyFilePath)
Set objFiles = objFolder.Files

Application.DisplayAlerts = False
Application.ScreenUpdating = False

'Insert New Sheet to hold Files list!
Set ws = Worksheets.Add

'Label File Information list!
With ws
.Cells(1, 1) = "Path: " & strMyFilePath: .Cells(1, 2) = "Name": .Cells(1, 3) = "Creation Date": .Cells(1, 4) = _
"Creation Author": .Cells(1, 5) = "Last Save Time": .Cells(1, 6) = "Last Author"
.Rows(1).Font.Bold = True
End With

'Add File information to sheet!
lngRowInfo = 2

For Each objThisFile In objFiles
If objThisFile.Type = "Microsoft Excel Worksheet" Then

Set wb = Workbooks.Open(strMyFilePath & "\" & objThisFile.Name, UpdateLinks:=False, ReadOnly:=True)

With ws
.Cells(lngRowInfo, 1) = strDirectory
.Cells(lngRowInfo, 2) = objThisFile.Name
.Cells(lngRowInfo, 3) = wb.BuiltinDocumentProperties("Creation Date")
.Cells(lngRowInfo, 4) = wb.BuiltinDocumentProperties("Author")
.Cells(lngRowInfo, 5) = wb.BuiltinDocumentProperties("Last Save Time")
.Cells(lngRowInfo, 6) = wb.BuiltinDocumentProperties("Last Author")
End With

wb.Close SaveChanges:=False
lngRowInfo = lngRowInfo + 1
End If
Next objThisFile

With ws
.Range("C:F").NumberFormat = "dd mmmm yyyy"
.Columns.AutoFit
End With
Exit Sub

'On Error Display: Error-information and Help option!
myError:

MsgBox "On ""OK"" will Exit you back to your sheet!" & vbLf & vbLf & _
"Error Source: " & Err.Source & vbLf & _
"Error Number: " & Err.Number & vbLf & _
"Error Type: " & Err.Description & vbLf _
, vbMsgBoxHelpButton _
, "Error Accessing, " & strMyFilePath & ", Drive: " & myDrive _
, Err.HelpFile _
, Err.HelpContext
GoTo myEnd

myEnd:
End Sub

Function GetFolder() As String
'Standard code module only, like: Module1.
Dim strItem$
Dim objFolderDialog As Object

Set objFolderDialog = Application.FileDialog(msoFileDialogFolderPicker)

With objFolderDialog
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath

If .Show <> -1 Then GoTo NextCode
strItem = .SelectedItems(1)
End With

NextCode:
GetFolder = strItem

Set objFolderDialog = Nothing
End Function
 
Upvote 0
Solution and Question: Search subdirectories for .xls files

I use the following code (borrowed from another site) to search through a directory and grab all the files with a certain extension:

First of all, you will need a UDF (User Defined Function):

Function FileList(fldr As String, Optional fltr As String = "*.xls") As Variant ' Change the *.xls to whatever file type you want to find

Dim sTemp As String, sHldr As String
If Right$(fldr, 1) <> "\" Then fldr = fldr & "\"
sTemp = Dir(fldr & fltr)
If sTemp = "" Then
FileList = False 'ensures an array is returned
Exit Function
End If
Do
sHldr = Dir
If sHldr = "" Then Exit Do
sTemp = sTemp & "|" & sHldr
Loop
FileList = Split(sTemp, "|")
End Function

Then you can use this UDF in your code like this:

Sub GetFiles()

Dim myPath As String

myPath = ActiveWorkbook.Path & "\[insert the path to the folder you want to search here]" ' Note that the path is relative to the current workbook
myvar = FileList(myPath, "*.xls") ' Change the *.xls to whatever you want to find

If TypeName(myvar) <> "Boolean" Then
For i = LBound(myvar) To UBound(myvar)
' What do you want to do with the name it finds? Suggest outputting to a cell:
Range("A1").Value = myPath ' or whatever you want to do, insert here
Next
End If
End Sub


Now for my question:
I can't figure out how to modify the code above to allow searching of the SUBDIRECTORIES

Can anyone please help me figure that out!?
 
Upvote 0
Tusharm,

I was looking for a solution to a problem with recursive dirs and found this thread. I read down to your first page post of code and started playing with it (not realizing there were 2 more pages of posts). When I saw what the script was doing as I stepped through it I literally LOLed with awe.

After a couple of hours of trying this and that and re-pasting your original code and starting over at least 3 times, I came up with a solution that works. I was going to come in and thank you, but found out you probably won't be back to this thread. Understandable.

I've tried to help here in what few threads I can, which isn't many. I feel good giving back to the community, but I watch the threads I've provided answers for and haven't really had any replies so I don't know if I've helped or not.

The amount of help I've gotten from this site in the last few months is nothing short of amazing. There are many like me who would agree.

So thank you Tusharm specifically for help on this project, and thanks to the rest of the MrExcel community for the time you've given us n00bies. :)
 
Upvote 0

Forum statistics

Threads
1,223,923
Messages
6,175,399
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