I am trying to do the following:
- specify a folder (containinf *.xlsm files)
- Iterate through all the files
- open each file, run a macro, close and save the file
- Move onto next file until all have been done.
The code below works, BUT the loop never ends... its as if every time I save the file that's just been worked on, it appears as a new item in the list of files to go through.
What am I doing wrong?
Thanks.
Sub runMe()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim MyPath As String
Dim wb As Workbook
Dim myDir As String
With Application
.ScreenUpdating = False
.DisplayAlerts = False
.EnableEvents = False
End With
myDir = "\templates"
Debug.Print ActiveWorkbook.Path
MyPath = ActiveWorkbook.Path & myDir
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object associated with the directory
Set objFolder = objFSO.GetFolder(MyPath)
'Loop through the Files
For Each objFile In objFolder.Files
If InStr(objFile.Name, "~") = 0 And InStr(objFile.Name, ".xlsm") <> 0 Then
Set wb = Workbooks.Open(objFile, 3)
Application.Run "'" & wb.Name & "'!doMacro"
wb.Close SaveChanges:=True
' Gets stuck in this loop
' WHY DOES IT KEEP LOOPING?
End If
Next
With Application
.ScreenUpdating = True
.DisplayAlerts = True
.EnableEvents = True
End With
End Sub
Workbooks.Opentakes aStringas a first argument (or something that can be cast to aString).FileCOM object is its path, you can cast it as string without problems. It's just not as explicit and obvious, but it works.