2

I have Excel-2007. I am using File System Object VBA code to list files in a directory. I have also set up reference to Microsoft Scriptlet Library in excel. I am getting:

Compiler error:User-defined type not defined

on this very first code line

Dim FSO As Scripting.FileSystemObject

Code used by me as follows:

 Sub ListFilesinFolder()

    Dim FSO As Scripting.FileSystemObject
    Dim SourceFolder As Scripting.Folder
    Dim FileItem As Scripting.File

    SourceFolderName = "C:\mydir"

    Set FSO = New Scripting.FileSystemObject
    Set SourceFolder = FSO.GetFolder(SourceFolderName)

    Range("A1:C1") = Array("text file", "path", "Date Last Modified")

    i = 2
    For Each FileItem In SourceFolder.Files
        Cells(i, 1) = FileItem.Name
        Cells(i, 2) = FileItem
        Cells(i, 3) = FileItem.DateLastModified
        i = i + 1
    Next FileItem

    Set FSO = Nothing

End Sub

Can someone point out where am I going wrong?

      **UPDATE -03-09-2015**   

I have updated my program based on @brettdj program and some research to list all files including sub-folder files. It works for me. I look forward to suggestions to further improve it.

      Sub ListFilesinFolder()
           Dim objFSO As Object
           Dim ws As Worksheet
           Dim cl As Range
           Dim objFolderName As String

           objFolderName = "C:\FY_2015-2016\sunil"
           Set objFSO = New Scripting.FileSystemObject

           Set ws = ActiveSheet 
           With Range("A1:C1")
             .Value2 = Array("File", "path", "Date Last Modified")
             .Font.Bold = True
           End With

           Set cl = ws.Cells(2, 1)

           ListFolders cl, objFSO.GetFolder(objFolderName)
           Set objFSO = Nothing
    End Sub

    Sub ListFolders(rng As Range, Fol As Scripting.Folder)
          Dim SubFol As Scripting.Folder
          Dim FileItem As Scripting.File
          ' List Files
          For Each FileItem In Fol.Files
             rng.Cells(1, 1) = FileItem.Name
             rng.Cells(1, 2) = FileItem.ParentFolder.Path
             rng.Cells(1, 3) = FileItem.DateLastModified
             Set rng = rng.Offset(1, 0)
          Next
        ' Proces subfolders
         For Each SubFol In Fol.SubFolders
              ListFolders rng, SubFol
         Next
         With ActiveSheet
            .Columns.EntireColumn.AutoFit
         End With
    End Sub

I am posting another update which is not cell by cell filling. REVISED UPDATE ON 3-09-2015

  Sub GetFileList()

    Dim strFolder As String
    Dim objFSO As Object
    Dim objFolder As Object
    Dim myResults As Variant
    Dim lCount As Long

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    ' Get the directory from the user
    With Application.FileDialog(msoFileDialogFolderPicker)
        .Show
        If .SelectedItems.Count = 0 Then Exit Sub
        'user cancelled
        strFolder = .SelectedItems(1)
    End With

    Set objFolder = objFSO.GetFolder(strFolder)

    'the variable dimension has to be the second one
    ReDim myResults(0 To 5, 0 To 0)

    ' place make some headers in the array
    myResults(0, 0) = "Filename"
    myResults(1, 0) = "Size"
    myResults(2, 0) = "Created"
    myResults(3, 0) = "Modified"
    myResults(4, 0) = "Accessed"
    myResults(5, 0) = "Full path"

    'Send the folder to the recursive function
    FillFileList objFolder, myResults, lCount

    ' Dump these to a worksheet
    fcnDumpToWorksheet myResults

    'tidy up
    Set objFSO = Nothing

    End Sub

Private Sub FillFileList(objFolder As Object, ByRef myResults As Variant, ByRef lCount As Long, Optional strFilter As String)

    Dim i As Integer
    Dim objFile As Object
    Dim fsoSubFolder As Object
    Dim fsoSubFolders As Object

    'load the array with all the files
    For Each objFile In objFolder.Files
        lCount = lCount + 1
        ReDim Preserve myResults(0 To 5, 0 To lCount)
        myResults(0, lCount) = objFile.Name
        myResults(1, lCount) = objFile.Size
        myResults(2, lCount) = objFile.DateCreated
        myResults(3, lCount) = objFile.DateLastModified
        myResults(4, lCount) = objFile.DateLastAccessed
        myResults(5, lCount) = objFile.Path
    Next objFile

    'recursively call this function with any subfolders
    Set fsoSubFolders = objFolder.SubFolders

    For Each fsoSubFolder In fsoSubFolders
        FillFileList fsoSubFolder, myResults, lCount
    Next fsoSubFolder

End Sub

Private Sub fcnDumpToWorksheet(varData As Variant, Optional mySh As Worksheet)

    Dim iSheetsInNew As Integer
    Dim sh As Worksheet, wb As Workbook
    Dim myColumnHeaders() As String
    Dim l As Long, NoOfRows As Long

    If mySh Is Nothing Then
        'make a workbook if we didn't get a worksheet
        iSheetsInNew = Application.SheetsInNewWorkbook
        Application.SheetsInNewWorkbook = 1
        Set wb = Application.Workbooks.Add
        Application.SheetsInNewWorkbook = iSheetsInNew
        Set sh = wb.Sheets(1)
    Else
        Set mySh = sh
    End If

    'since we switched the array dimensions, have to transpose
    With sh
        Range(.Cells(1, 1), .Cells(UBound(varData, 2) + 1, UBound(varData, 1) + 1)) = _
            Application.WorksheetFunction.Transpose(varData)

        .UsedRange.Columns.AutoFit
    End With

    Set sh = Nothing
    Set wb = Nothing

End Sub
skkakkar
  • 2,772
  • 2
  • 17
  • 30
  • Are you looking to get all file details, or only *txt* file details. – brettdj Sep 03 '15 at 01:29
  • All file details please in Second Phase. Presently worked for txt files only as a sample to establish and prove the program code. – skkakkar Sep 03 '15 at 02:08
  • @skkhar don't populate the data cell by cell, look at using an array as I did. – brettdj Sep 03 '15 at 07:57
  • I would be grateful if you kindly update your answer to list all files in directories and sub directories which will help me a lot in right way of placing code for my future programs. Thanks – skkakkar Sep 03 '15 at 08:18
  • for a recursive process take a look at http://stackoverflow.com/questions/9827715/get-list-of-subdirs-in-vba/9832978#9832978 – brettdj Sep 03 '15 at 09:24
  • @brettdj I am posting another update. Hope it is in-line with your suggestion – skkakkar Sep 03 '15 at 09:47

3 Answers3

1

You're referencing Microsoft Scriptlet Library; should be Microsoft Scripting Runtime.

Andy Brown
  • 5,309
  • 4
  • 34
  • 39
1

Try this:

Sub ListFilesinFolder()

    Dim FSO
    Dim SourceFolder
    Dim FileItem

    SourceFolderName = "C:\mydir"

    Set FSO = CreateObject("Scripting.FileSystemObject") '<-- New change
    Set SourceFolder = FSO.GetFolder(SourceFolderName)

    Range("A1:C1") = Array("text file", "path", "Date Last Modified")

    i = 2
    For Each FileItem In SourceFolder.Files
        Cells(i, 1) = FileItem.Name
        Cells(i, 2) = FileItem
        Cells(i, 3) = FileItem.DateLastModified
        i = i + 1
    Next FileItem

    Set FSO = Nothing

End Sub
ManishChristian
  • 3,759
  • 3
  • 22
  • 50
1

Would recommend using an array approach for speed

Sub ListFilesinFolder()

    Dim objFSO As Object
    Dim objFolder As Object
    Dim objFile As Object
    Dim lngCnt As Long
    Dim X

    objFolderName = "C:\temp"

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFSO.GetFolder(objFolderName)


    ReDim X(1 To objFolder.Files.Count, 1 To 3)

    For Each objFile In objFolder.Files
        lngCnt = lngCnt + 1
        X(lngCnt, 1) = objFile.Name
        X(lngCnt, 2) = objFile.Path
        X(lngCnt, 3) = Format(objFile.DateLastModified, "dd-mmm-yyyy")
    Next

    [a2].Resize(UBound(X, 1), 3).Value2 = X

    With Range("A1:C1")
        .Value2 = Array("text file", "path", "Date Last Modified")
        .Font.Bold = True
        .Columns.EntireColumn.AutoFit
    End With

End Sub
brettdj
  • 54,857
  • 16
  • 114
  • 177
  • Taking cue from your program and some research, I have updated the program to list all files in directories and sub directories. Look forward to your opinion to further refine and improve it. Thanks a lot. – skkakkar Sep 03 '15 at 07:50
  • I would be grateful if you kindly update your answer to list all files in directories and sub directories which will help me a lot in right way of placing code for my future programs. Thanks – skkakkar Sep 03 '15 at 08:36
  • I have posted revised update which is not based on cell by cell filling method. Hope it meets your approval – skkakkar Sep 03 '15 at 10:11