Hi
I have around 50 files in the directory. I want macro to open the files one by one and run the macro saved in all files. Below is the code I have.,.....it opens one file, runs the macro and closes. it does not open any files listed in the directory.
Please assist.
Sub OpenAndRunMacro()
Dim wb As Workbook
Dim folderPath As String
Dim filename As String
' Disable alerts to prevent pop-up windows
Application.DisplayAlerts = False
' Define the folder path
folderPath = "C:\Users\C.ABC\OneDrive - ABC\Current_Week\"
' Check if the folder exists
If Dir(folderPath, vbDirectory) <> "" Then
' Loop through each file in the folder
filename = Dir(folderPath & "*.xls*")
Do While filename <> ""
' Open the workbook
Set wb = Workbooks.Open(folderPath & filename)
' Run the macro if it exists
On Error Resume Next
Application.Run "'" & wb.Name & "'!CopyAndPasteStock"
On Error GoTo 0
' Close the workbook without saving changes
wb.Close False
' Get the next filename
filename = Dir
Loop
Else
MsgBox "Folder not found!"
End If
' Enable alerts back
Application.DisplayAlerts = True
MsgBox "Process completed."
End Sub
I have around 50 files in the directory. I want macro to open the files one by one and run the macro saved in all files. Below is the code I have.,.....it opens one file, runs the macro and closes. it does not open any files listed in the directory.
Please assist.
Sub OpenAndRunMacro()
Dim wb As Workbook
Dim folderPath As String
Dim filename As String
' Disable alerts to prevent pop-up windows
Application.DisplayAlerts = False
' Define the folder path
folderPath = "C:\Users\C.ABC\OneDrive - ABC\Current_Week\"
' Check if the folder exists
If Dir(folderPath, vbDirectory) <> "" Then
' Loop through each file in the folder
filename = Dir(folderPath & "*.xls*")
Do While filename <> ""
' Open the workbook
Set wb = Workbooks.Open(folderPath & filename)
' Run the macro if it exists
On Error Resume Next
Application.Run "'" & wb.Name & "'!CopyAndPasteStock"
On Error GoTo 0
' Close the workbook without saving changes
wb.Close False
' Get the next filename
filename = Dir
Loop
Else
MsgBox "Folder not found!"
End If
' Enable alerts back
Application.DisplayAlerts = True
MsgBox "Process completed."
End Sub