Loop Through Files to Find Specific Files - excel

I am trying to set up a macro where you can open certain files with a certain name without having to go through the files I have already filtered through.
In the code before this macro, it loops through an entire folder, and opens all of the files that meet a criteria, pull a number from there, pastes into the new workbook, closes that workbook, and goes to the next file.
I have the criteria in a range in the current workbook, and I want to use that criteria when determining which workbooks to open in the folder.
I'm wondering if there is a way to start looping through the folder starting with the last file that was opened using the macro before.
EDIT: The following code is what I have so far.
Sub LoopThroughFilesInFolder()
'=============================================================================
'Looping through all of the files in the folder, and grabbing the last value
'=============================================================================
Dim wb As Workbook
Dim MyPath As String
Dim MyFile As String
Dim myExtension As String
Dim FolderPicker As FileDialog
Application.ScreenUpdating = False
'Retrieve Target Folder Path From User
Set FolderPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FolderPicker
.Title = "Select a Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
MyPath = .SelectedItems(1) & "\"
End With
'In case of cancel
NextCode:
MyPath = MyPath
If MyPath = "" Then GoTo ResetSettings
'Target File Extension
myExtension = "*1*9 Restraint*.xls*"
'Target Path with Ending Extension
MyFile = Dir(MyPath & myExtension)
'Loop through each Excel file in folder
LastRow = Sheets("Sheet Name").Cells(Rows.Count, 1).End(xlUp).Row
i = LastRow - 1
Do While MyFile <> ""
If MyFile Like Cells(LastRow, 1).Value Then
Set wb = Workbooks.Open(Filename:=MyPath & MyFile, ReadOnly:=True)
'Ensure Workbook has opened before moving on
DoEvents
'Find last row
LastRow = ActiveSheet.Cells(Rows.Count, 2).End(xlUp).Row
'Grab value next to last row
LastValue = ActiveSheet.Cells(LastRow, 2).Value
If WorksheetFunction.IsNumber(LastValue) = False Then
LastValue = ActiveSheet.Cells(LastRow, 3).Value
End If
'Go back to graph workbook
Workbooks("Workbook Name").Sheets("Sheet Name").Cells(i, 2).Value = MyFile
Workbooks("Workbook Name").Sheets("Sheet Name").Cells(i, 3).Value = LastValue
i = i + 1
wb.Close savechanges:=False
DoEvents
MyFile = Dir
End If
Loop
'Reset Macro Optimization Settings
ResetSettings:
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
This is looping through the entire folder (there are about 1000 files). My question above assumes that we have already done this macro, and the macro I am trying to currently write will only open the most recent files matching a certain criteria, still from the same folder though (but without having to loop through the files that were already opened from the previous macro).

Dir$() without a new file pattern retrieves the next matching file (Win32 FindNextFile), whereas Dir$(file pattern) starts the search over again, even if the pattern is the same as the previous one (Win32 FindFirstFile).
That being said, maybe do something like
Static bolBeenHere As Boolean
If bolBeenHere = False Then
' First search, use the file search pattern
' Target Path with Ending Extension
MyFile = Dir(MyPath & myExtension)
bolBeenHere = True
Else
' Retrieve the next matching file
MyFile = Dir$()
End If
' Stuff
Do While MyFile <> ""
...
Loop
A small performance advice. Use
Do While Len(MyFile) > 0
instead of
Do While MyFile <> ""
A string comparison "costs" more than a numeric comparison.

Related

Read a file and creat a table

I'm looking for a help in a difficult mission.
I have more then 30.000 files in a especific folder (*\backup) in xl?? format and need to read the cell B4. I thought the better idea is use the VBA in Excel to read this specific cell for each file and write on a table A:B.
I believe the following should help you, just remember to amend the declaration for the destination Worksheet name and the full path to the folder where the Workbooks you want to read reside.
The code below will loop through your desired Directory/Folder and read all the files with an .xls* extension, get the value from the first Worksheet in cell B4 and pass this value to the destination worksheet.
Sub LoopAllExcelFilesInFolder()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim wsDestination As Worksheet: Set wsDestination = ThisWorkbook.Worksheets("Sheet1")
'declare and set the worksheet where you want to aggregate the data.
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.CutCopyMode = False
myPath = "C:\backup\"
'set the full path to the folder you want to utilize, remember to add the last \
Last = wsDestination.Cells(wsDestination.Rows.Count, "A").End(xlUp).Row
If Last >= 2 Then wsDestination.Range("A2:B" & Last).ClearContents
'clear the destination worksheet ready to aggregate again
myExtension = "*.xls*"
'Target File Extension (must include wildcard "*")
myFile = Dir(myPath & myExtension)
'Target Path with Ending Extention
Do While myFile <> ""
'Loop through each Excel file in folder
Set wb = Workbooks.Open(Filename:=myPath & myFile)
DoEvents
'Ensure Workbook has opened before moving on to next line of code
wsDestination.Cells(1, "A").Value = "Filename"
wsDestination.Cells(1, "B").Value = "Value From Cell B4"
NextRow = wsDestination.Cells(wsDestination.Rows.Count, "A").End(xlUp).Offset(1, 0).Row
wsDestination.Cells(NextRow, "A").Value = myFile
wsDestination.Cells(NextRow, "B").Value = wb.Worksheets(1).Range("B4").Value
wb.Close SaveChanges:=False
'Close Workbook without Saving
DoEvents
'Ensure Workbook has closed before moving on to next line of code
myFile = Dir
'Next File
Loop
MsgBox "Transfer of Data Completed!", vbInformation, "Info"
'Message Box when tasks are completed
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub

How can I paste data from one spreadsheet to the last column of another?

Im trying to copy data from a whole bunch of different workbooks into one master sheet, pasting just the values in the next blank column. It all seems to be functional but always fails when it attempts to paste into the master sheet. I've tried looking at similar problems elsewhere but i cant seem to get them to work with what I am trying to do.
I have grabbed the bulk of this code off somewhere else and modified to suit, as you may be able to tell from some of the left over comments
Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim colDest As Long
Dim Dest As Worksheet
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(fileName:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Change First Worksheet's Background Fill Blue this is where the work occurs
Set Dest = Workbooks("Master.xlsm").Worksheets(1)
colDest = Dest.Cells(1, Dest.Columns.Count).End(xlToRight).Column
wb.Worksheets(1).Range("b3:u83").Copy
Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
EDIT: Error occurs on this line:
Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues
Run-time error '1004':
Method 'Range' of object '_Worksheet' failed.
EDIT2: Changing the attempt to Paste with an attempt to write a value to the cell ie:
Dest.Cells(1, colDest) = "Test"
Correctly types "Test" into the next available column on the master sheet for every workbook that was opened from the directory.
Apparently changing 'Range' to 'Cells' works, which i thought i tried yesterday but was throwing a different error complaining i wasn't selecting the correct size cell
Try this basically what you need to do is add 1 to the colDest to give you the next empty column.
Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim colDest As Long
Dim Dest As Worksheet
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(fileName:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Change First Worksheet's Background Fill Blue this is where the work occurs
Set Dest = Workbooks("Master.xlsm").Worksheets(1)
colDest = Dest.Cells(1, Dest.Columns.Count).End(xlToLeft).Column + 1
wb.Worksheets(1).Range("b3:u83").Copy
Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Below are some guidelines on how to find last column an import value after last column.
Option Explicit
Sub Test()
Dim LastColumn As Long
With ThisWorkbook.Worksheets("Sheet1")
'Last Column using UsedRange (NOT A GOOD IDEA)
LastColumn = .UsedRange.Columns(.UsedRange.Columns.Count).Column
'Last Column using specific row 7
LastColumn = .Cells(7, .Columns.Count).End(xlToLeft).Column
'Add a value in row 5 & after last column
.Cells(5, LastColumn + 1).Value = ""
End With
End Sub
Set Dest = Workbooks("Master.xlsm").Worksheets(1)
colDest = Dest.Cells(1, Dest.Columns.Count).End(xlToLeft).Column + 1
wb.Worksheets(1).Range("b3:u83").Copy
Dest.Cells(1, colDest).PasteSpecial Paste:=xlPasteValues
Correctly inputs the Data where I need it, the 'ToLeft' made a difference but 'Range' wouldn't allow me to paste where 'Cells' does

VBA Loop through folder and subfolders to find specific sheet then Copy and Paste certain data

I hope you can help. I have made an attempt to code this myself (see code below) but failed so I am reaching out to the community for assistance.
What I need my code to do is allow a user to click on a command button, then the user selects a folder. Once this folder is selected. I need the code to look or loop through this folder and all the subfolders in this folder and find sheets with a name Like "CustomerExp" then copy the the data in sheets name Like "CustomerExp" from the second row down to the last used row and paste the information into a sheet called "Disputes" where the macro is housed.
I have supplied pictures for better understanding.
Pic 1 is where the macro is housed and where i need the info pasted to.
Pic 1
Pic 2 is the first file the user will select and the only one i want them to select
Pic 2
Pic 3 you can see that in folder 2017 there are several other folders
Pic 3
Pic 4 Again you can see that we have the file I am looking for plus more folders that need to be looped through
Pic 4
Essentially what I need the code to do is allow the person to select 2017 folder click ok and then the code goes through everything in the 2017 folder finds the files with names Like "CustomerExp" copies data and pastes to the sheet "Disputes" in the sheet where the macro is held.
My code compiles but its not doing anything. As always any and all help is greatly appreciated.
MY CODE
Sub AllWorkbooks()
Dim MyFolder As String 'Path collected from the folder picker dialog
Dim myFile As String 'Filename obtained by DIR function
Dim wbk As Workbook 'Used to loop through each workbook
Dim FSO As New FileSystemObject ' Requires "Windows Script Host Object Model" in Tools -> References
Dim ParentFolder As Object, ChildFolder As Object
Dim wb As Workbook
Dim myPath As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim lRow As Long
Dim ws2 As Worksheet
Dim y As Workbook
On Error Resume Next
Application.ScreenUpdating = False
'Opens the folder picker dialog to allow user selection
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder"
.Show
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then 'If no folder is selected, abort
MsgBox "You did not select a folder"
Exit Sub
End If
MyFolder = .SelectedItems(1) & "\" 'Assign selected folder to MyFolder
End With
myFile = Dir(MyFolder) 'DIR gets the first file of the folder
Set y = ThisWorkbook
Set ws2 = y.Sheets("Disputes")
'Loop through all files in a folder until DIR cannot find anymore
Do While myFile <> ""
If myFile Like "*CustomerExp*" Then
'Opens the file and assigns to the wbk variable for future use
Set wbk = Workbooks.Open(Filename:=MyFolder & myFile)
'Replace the line below with the statements you would want your macro to perform
With wb.Sheets(1)
lRow = .Range("A" & Rows.Count).End(xlUp).Row
.Range("A2:M" & lRow).Copy ws2.Range("A" & Rows.Count).End(xlUp)(2)
End With
Application.Wait (Now + TimeValue("0:00:05"))
wbk.Close savechanges:=True
End If
myFile = Dir 'DIR gets the next file in the folder
Loop
For Each ChildFolder In FSO.GetFolder(MyFolder).SubFolders
myFile = Dir(MyFolder & ChildFolder.Name) 'DIR gets the first file of the folder
'Loop through all files in a folder until DIR cannot find anymore
Do While myFile <> ""
If myFile Like "*CustomerExp*" Then
'Opens the file and assigns to the wbk variable for future use
Set wbk = Workbooks.Open(Filename:=MyFolder & ChildFolder.Name & "\" & myFile)
'Replace the line below with the statements you would want your macro to perform
With wb.Sheets(1)
lRow = .Range("A" & Rows.Count).End(xlUp).Row
.Range("A2:M" & lRow).Copy ws2.Range("A" & Rows.Count).End(xlUp)(2)
End With
Application.Wait (Now + TimeValue("0:00:05"))
wbk.Close savechanges:=True
End If
myFile = Dir 'DIR gets the next file in the folder
Loop
Next ChildFolder
Application.ScreenUpdating = True
End Sub
Just couple of minor issues in your code:
1. With wb.Sheets(1) should be With wbk.Sheets(1)
followed by
lRow = .Range("A" & Rows.Count).End(xlUp).Row should be lRow = .Range("A" & .Rows.Count).End(xlUp).Row
as already pointed out by #ShaiRado in comments
You have to make above changes at two places. First in
Do While myFile <> ""
Loop
and then again in do while loop inside for each loop
For Each ChildFolder In FSO.GetFolder(MyFolder).SubFolders
Do While myFile <> ""
Loop
Next ChildFolder
2. myFile = Dir(MyFolder & ChildFolder.Name) should be myFile = Dir(MyFolder & ChildFolder.Name & "\")

Open multiple CSV files, sort and filter the data from each one, place in master spreadsheet Macro/VBA

I am trying to:
open up spreadsheets from a folder of 50
sort and filter the first sheet on each one (the name will be unknown of this sheet)
filtering needs to find each row that has a certain value in column J - this value is 'No'
All rows that meet the criteria (row J contains 'no') need to be then placed onto a master spreadsheet
Each csv should close each time it's been processed
I have spent hours & hours on forums and have some code which I have been tinkering with, but can't get it running together:
Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.csv*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
Range("A1:AC3100").Select
Selection.AutoFilter
ActiveWindow.LargeScroll ToRight:=1
Range("Y2").Select
ActiveSheet.Range("$A$1:$AC$3110").AutoFilter Field:=25, Criteria1:="No"
Range("A1:AC3100").Select
Range("Y2").Activate
Selection.Copy
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Paste
Application.CutCopyMode = False
Selection.Copy
Windows("Book1").Activate
Rows("1:1").Select
Selection.Insert Shift:=xlDown
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
The spreadsheet data has variable lengths do I made the selection the maximum:
Range("A1:AC3100")
I would assume there is a better way than this too.
Your criterion is a bit too vague to give a perfect response, but I'll take a crack at it. Some parts of your code seem extraneous or convoluted so I'm doing this based on your end goal (all rows where the value in column J for the first sheet in each workbook that contain 'no' are copied into a master spreadsheet).
If all of your worksheets are always in the same folder you can make the myPath static rather than attempting to use the msoFileDialogFolderPicker. When I attempted to run your code on my machine it gave me an "Out of Memory" error, if you have this issue as well I recommend a static string for myPath.
Option Explicit
Sub PutInMasterFile()
Dim wb As Workbook
Dim masterWB As Workbook
Dim rowNum As Integer
Dim copyRange As Range
Dim pasteRange As Range
Dim myPath As String
Dim myFile As String
Dim FirstAddress As String
Dim x As Variant
Dim c As Variant
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
I would advise against disabling Events until you have confirmed your code is running correctly. Worry about getting working code before thinking about optimization.
x = 1
Set masterWB = Workbooks("NAMEOFWORKBOOK")
Set pasteRange = masterWB.Sheets(1).Range("A" & x)
myPath = "C:\EXAMPLE\MOREEXAMPLE\*.csv"
myFile = Dir(myPath)
myPath can be set to search directly for .csv files in the string.
Do While myFile <> vbNullString
Workbooks.Open (myFile)
With Workbooks(myFile).Sheets(1)
Set c = .Range("J:J").Find("No", LookIn:=xlValues, lookat:=xlWhole)
Using .find in vba is preferential to trying to get a filter and then grabbing everything that the filter displays.
If Not c Is Nothing Then
FirstAddress = c.Address
Do
rowNum = c.Row
Set copyRange = .Range(rowNum & ":" & rowNum)
copyRange.Copy
pasteRange.PasteSpecial
x = x + 1
Set pasteRange = masterWB.Sheets(1).Range("A" & x)
Copies in the row into your master sheet. The x = x + 1 guarantees you paste new data onto a new row to avoid overwriting anything.
Set c = .Range("J:J").FindNext(c)
Loop While Not c Is Nothing And FirstAddress <> c.Address
End If
End With
Workbooks(myFile).Close
myFile = Dir()
Closes your first file and gets the next one set up
Set pasteRange = masterWB.Sheets(1).Range("A" & x)
Sets the paste range in the master wb outside of the inner loop, otherwise it will overwrite the values starting at A1 again with the next file.
Loop
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
I would also recommend you read up on VBA best practices for any future code you work on such as using Option Explicit and avoiding use of GoTo or .Select wherever possible.

Open and read from excel file

Edit: After user3561813 the suggestion of adding "/", it now read the first file. I have an out of range error message "9". It does read the first file correctly. Ultimately I am trying to open each file, and read the name and age (this is a testing not the real production form). And retrieve the values back to my main worksheet.
Original question
I am trying to read hundred of excel forms in a folder, read a particular cell position, and record them into my testing worksheet. I googled this tutorial and tried to write my code. But when I execute the Getting Folder function, selected a folder path, it does not loop the excel files I have. (or record their names)
'Source: https://www.youtube.com/watch?v=7x1T4s8DVc0
Sub GettingFolder()
Dim SelectedFolder As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select folder"
.ButtonName = "Confirm"
.InitialFileName = "U:\"
If .Show = -1 Then
'ok clicked
SelectedFolder = .SelectedItems(1)
MsgBox SelectedFolder
' This is where I want to call my function
LoopFiles (SelectedFolder)
Else
'cancel clicked
End If
End With
End Sub
' Source: http://www.excel-easy.com/vba/examples/files-in-a-directory.html
Sub LoopFiles(path As String)
Dim directory As String, fileName As String, sheet As Worksheet
Dim i As Integer, j As Integer
' Avoid Screen flicker and improve performance
Application.ScreenUpdating = False
' Fixed per suggestion below..
directory = path & "\"
fileName = Dir(directory & "*.xl??")
Do While fileName <> ""
i = i + 1
j = 2
Cells(i, 1) = fileName
Workbooks.Open (directory & fileName)
For Each sheet In Workbooks(fileName).Worksheets
Workbooks("Testing.xlsm").Worksheets(1).Cells(i, j).Value = sheet.Name
j = j + 1
Next sheet
Workbooks(fileName).Close
fileName = Dir()
Loop
' Reset the screen update setting
Application.ScreenUpdating = True
End Sub
Interesting question! This should do it for you. Modify as needed.
Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xlsx"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
Row = 1
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Change First Worksheet's Background Fill Blue
ThisWorkbook.Worksheets("Sheet1").Range("A" & Row).Value = Worksheets(1).Range("A1").Value
Row = Row + 1
'Save and Close Workbook
wb.Close SaveChanges:=True
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
In your code, the path variable may not contain a trailing backslash. This causes the following code in your LoopFiles(<>) SubRoutine to be inaccurate:
directory = path
fileName = Dir(directory & "*.xl??")
Filename would look something like: c:\users\name\documentshello.xlsx
Try changing the above code to:
directory = path & "\"
fileName = Dir(directory & "*.xl??")
Does that fix the problem?

Resources