Hi Ben,
FileSearch won't work in all cases because you are using Excel 2007
This is what I use as a generic looping code:
Sub Generic_Loop_Through_Files()
Dim CalcMode As Long
Dim screenUpdateState As Variant
Dim statusBarState As Variant
Dim eventsState As Variant
Dim fso As Object
Dim fpath As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please Select a Folder"
.ButtonName = "Select Folder"
.InitialFileName = "C:\Users\HP-Server\Desktop\"
.AllowMultiSelect = False
.Show
If .SelectedItems.Count > 0 Then
fpath = .SelectedItems(1) & "\"
Else
MsgBox "No folder was chosen." & vbLf & vbLf & "Please try again.", vbExclamation, "User Cancelled."
Exit Sub
End If
End With
' Turn off some Excel functionality so your code runs faster
screenUpdateState = Application.ScreenUpdating
statusBarState = Application.DisplayStatusBar
eventsState = Application.EnableEvents
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.DisplayStatusBar = False
.EnableEvents = False
.DisplayAlerts = False
End With
' Use File System Object to choose folder with files
Set fso = CreateObject("Scripting.FileSystemObject")
'Call the ProcessFolders macro to loop through folders
Call ProcessFolders(fso, fpath)
' Turn Excel functionality back on
With Application
.Calculation = CalcMode
.ScreenUpdating = screenUpdateState
.DisplayStatusBar = statusBarState
.EnableEvents = eventsState
.Calculation = CalcMode
End With
MsgBox "Automation completed...", vbInformation
End Sub
Sub ProcessFolders(ByRef fso, ByVal fpath)
Dim myFolder, mySubFolder, myFile
Dim wkb As Workbook
Dim SavePath As String
' Open each file consequently
Set myFolder = fso.GetFolder(fpath)
For Each myFile In myFolder.Files
If LCase(myFile.Name) Like "*.xls*" Then
' Perform tasks with each file
Set wkb = Workbooks.Open(myFile)
' First worksheet only - change according to needs
With wkb.Worksheets(1)
'*******************************************
'* Add code to do something with each file *
'*******************************************
End With
' 'Save file in original folder, but as a different file format (Option 1)
' wkb.SaveAs Left(myFile, InStr(1, myFile, ".xls") - 1), xlCSV
' ' Save file in original folder, but as different file format (Option 2)
' SavePath = fso.GetFolder(fpath).Name & "\" & fso.GetBaseName(myFile) & ".xls"
' wkb.SaveAs fileName:=SavePath, FileFormat:=xlNormal, CreateBackup:=False
' Close file (saving = True)
wkb.Close savechanges:=True
End If
' Loop through all files in folder
Next myFile
' Loop through all subfolders
For Each mySubFolder In myFolder.SubFolders
Call ProcessFolders(fso, mySubFolder)
Next mySubFolder
End Sub
Good luck.
abousetta
Bookmarks