I'm trying to do some code on a folder system with hundreds of excel files. The code I have is only applicable to some of the files and I want those to be amended and saved. The rest are to be ignored.
I have adapted the code from Excel VBA: Loop Through a Folder of Excel Workbooks. FileSearch Method and have attempted to add in some error handling to skip over the files that are not applicable.
For some reason the error handling works for the first file but then the second time I just get a run-time error again. Any ideas?
Here is my code
I have adapted the code from Excel VBA: Loop Through a Folder of Excel Workbooks. FileSearch Method and have attempted to add in some error handling to skip over the files that are not applicable.
For some reason the error handling works for the first file but then the second time I just get a run-time error again. Any ideas?
Here is my code
Code:
Sub RunCodeOnAllXLSFiles()Dim lCount As Long
Dim wbResults As Workbook
Dim wbCodeBook As Workbook
Dim FailPath As String
Dim CurrentSheet As Worksheet
Dim FileToOpen As Variant
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
Set wbCodeBook = ThisWorkbook
With Application.FileSearch
.NewSearch
.LookIn = "C:\test_folder"
.SearchSubFolders = True
.FileType = msoFileTypeExcelWorkbooks
If .Execute > 0 Then 'Workbooks in folder
For lCount = 1 To .FoundFiles.Count 'Loop through all
'Open Workbook x and Set a Workbook variable to it
Set wbResults = Workbooks.Open(Filename:=.FoundFiles(lCount), UpdateLinks:=0)
'lots of code goes here (dealing with graphs)
wbResults.Close SaveChanges:=True
Failed:
'record the failed units in log file
If Err.Number <> 0 Then
Open "C:\FailLog.txt" For Append As #1 'if file does not exist, it will be created
Print #1, Application.ActiveWorkbook.FullName
Close #1
wbResults.Close SaveChanges:=False
On Error GoTo 0
Resume
End If
Next lCount
End If
End With
On Error GoTo 0
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
End Sub