VBA List All Headers in the worksheet for each file in a folder

lager1001

Board Regular
Joined
May 17, 2019
Messages
88
I have a folder with thousands of files. Some of these files have misnamed columns and I need to weed them out. Rather than opening them one by one I'd like to have a VBA script that will loop through all the files and grab the file name and then list the headers in the columns to the right of the file name, for each file.

Any ideas?
 

Excel Facts

Best way to learn Power Query?
Read M is for (Data) Monkey book by Ken Puls and Miguel Escobar. It is the complete guide to Power Query.
I believe that the macro would have to open each file, pull the headers and then close each file. Do you want to pull the headers from the first sheet in each file? What is the full path to the folder containing the files? What is the file extension (xlsx, xlsm)? Are those files the only files in that folder?
 
Upvote 0
Assuming that the headings are, on the first sheet of each workbook, in row 1 and start in cell A1, try this:

Change "C:\trabajo\" for your folder

VBA Code:
Sub GetHeadears()
  Dim wb As Workbook
  Dim sh As Worksheet
  Dim sPath As String
  Dim sFile As Variant
  Dim i As Long, lc As Long
  
  Application.ScreenUpdating = False
  Application.DisplayAlerts = False
  
  sPath = "C:\trabajo\"
  sFile = Dir(sPath & "*.xls*")
  Set sh = Sheets("Sheet1")
  sh.Cells.ClearContents
  i = 2
  
  Do While sFile <> ""
    Set wb = Workbooks.Open(sPath & sFile)
    lc = wb.Sheets(1).Cells(1, Columns.Count).End(1).Column
    sh.Range("A" & i).Value = sFile
    sh.Range("B" & i).Resize(1, lc).Value = wb.Sheets(1).Range("A1").Resize(1, lc).Value
    i = i + 1
    wb.Close False
    sFile = Dir()
  Loop
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,788
Messages
6,121,597
Members
449,038
Latest member
Arbind kumar

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