File names to excel from respective folders

harinsh

Active Member
Joined
Feb 7, 2012
Messages
259
Hi All,


I am working on some automation and need your help in vba code to get excel file names from respective folders......for example ..I have 10 different folders and need the file names those were inside the folder to excel cell starting from A1, A2, A3...so on...


if I get the complete path it would even really help me.....


Thanks in advance...
 

MrIfOnly

Active Member
Joined
Nov 10, 2016
Messages
489
This code will put the file name in column A and the full path in column B. You'll have to put the folder paths in the folderlist array in the first sub.

Code:
Option Explicit

Dim fs, f1, f, fc
Dim n As String
Dim r As Integer, c As Integer
Dim folderspec As String


Sub folderloop()
Dim folderlist() As String
Dim x As Integer


Worksheets(1).Columns("A:B").ClearContents


folderlist = Split("C:\Users\username\folder1,C:\Users\username\folder2,C:\Users\username\folder3,C:\Users\username\folder4", ",")


r = 2


For x = 0 To 9
    folderspec = folderlist(x)
    listFiles
Next x


End Sub


Sub listFiles()
    With Worksheets(1)
        .Range("A1").Value = "File Name"
        .Range("B1").Value = "Full Path"
        .Range("A1:B1").Font.Bold = True
    End With
            
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(folderspec)
    Set fc = f.Files
    
    For Each f1 In fc
        If fs.GetExtensionName(f1) = "xls" Or fs.GetExtensionName(f1) = "xlsm" Then
            Sheets(1).Cells(r, 1) = fs.GetBaseName(f1)
            Sheets(1).Cells(r, 2) = f1
            r = r + 1
        End If
    Next
End Sub
Regards,

CJ
 
Last edited:

Forum statistics

Threads
1,081,615
Messages
5,360,037
Members
400,565
Latest member
Tommy O

Some videos you may like

This Week's Hot Topics

  • VBA (Userform)
    Hi All, I just would like to know why my code isn't working. Here is my VBA code: [CODE=vba]Private Sub OKButton_Click() Dim i As Integer...
  • List box that changes fill color
    Hello, I have gone through so many pages trying to figure this out. I have a 2020 calendar that depending on the day needs to have a certain...
  • Remove duplicates and retain one. Cross-linked cases
    Hi all I ran out of google keywords to use and still couldn't find a reference how to achieve the results of a single count. It would be great if...
  • VBA Copy and Paste With Duplicates
    Hello All, I'm in need of some input. My VBA skills are sub-par at best. I've assembled this code from basic research and it works but is...
  • Macro
    is it possible for a macro to run if the active cell value is different to the value above it
  • IF DATE and TIME
    I currently use this to check if date has passed but i also need to set a time on it too. Is it possible? [CODE=vba]=IF(B:B>TODAY(),"Not...
Top