EnableEvents not working - excel

I'm new to VBA and am having an issue developing the code below. The code will hopefully run through about 500+ files and extract some data from various cells. Once I get this issue with the enableevents out the way.
At present, every xls file pops up with the “enable or disable macro” box. Any help will be great.
Sub ProcessAll(Optional sPath As Variant)
Dim WB As Workbook, sFile As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
If IsMissing(sPath) Then
sPath = "U:\Desktop\Temp\PEP Temp\"
sFile = Dir(sPath & "*.xls")
End If
'Loop through all .xls-Files in that path
Do While sFile <> ""
Set WB = Workbooks.Open(sPath & sFile, , ReadOnly = True, , , , , , , , Notify = False)
Debug.Print WB.Name
WB.Close False
sFile = Dir
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
End Sub
After doing some research i found that you can force excel to select disable macros with the following line of code
Application.AutomationSecurity = msoAutomationSecurityForceDisable

From Excel Menu:
Files > Confidentiality center > Parameters > macros Parameters > choose wich one you need.
i tried to turn it into a vba macro using develeopper> record macro, but no success...
so i think you must do it manually.

Related

Run a specific macro in different workbook

I have a folder with more than 300+ excel files and what I want to open each of the excel files inside the folder and run specific macro that's already stored in each of the excel files, save it, close it and move to the next file.
The macro which is stored in each excel file is connected to other macros inside the workbook, you could call it like a Main macro, so for example If I just tried to run the Main macro, without the macros it's connected, to all the files at the same time, it just wouldn't work, because it is connected to other macros. The code below is what I've done so far, but it doesn't work as intended
Sub run_mYearChange
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
ActiveSheet.DisplayPageBreaks = False
Dim wb As Workbook, ws As Worksheet
Dim wPath As String, wQuan As Long, n As Long
Dim fso As Object, folder As Object, subfolder As Object, wFile As Object
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
If .Show <> -1 Then Exit Sub
wPath = .SelectedItems(1)
End With
Set fso = CreateObject("scripting.filesystemobject")
Set folder = fso.getfolder(wPath)
wQuan = folder.Files.Count
n = 1
For Each wFile In folder.Files
Application.StatusBar = "Processing folder : " & folder & ". File : " & n & " of : " & wQuan
If Right(wFile, 4) Like "*xlsm*" Then
Set wb = Workbooks.Open(wFile)
Application.Run "'C:\test2\*.xlsm*'!mYearChange.YearChangeFunction"
wb.Save True
wb.Close True
End If
n = n + 1
Next
Set fso = Nothing: Set folder = Nothing: Set wb = Nothing
MsgBox "End"
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True
ActiveSheet.DisplayPageBreaks = True
End Sub
I'm trying to find a solution everywhere and without luck. In this website there also hasn't been anything similar to what I'm asking. I would love all the help I could get, I'm kind of desperate, because nothing works.
Thank you for your help in advance.
You need to adjust the file name for each file opened.
Untested:
Sub run_mYearChange
'snipped....
Dim wPath As String, n As Long, f
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
If .Show <> -1 Then Exit Sub
wPath = .SelectedItems(1)
End With
if right(wPath, 1) <> "\" then wPath = wPath & "\"
f = Dir(wPath & "*.xlsm")
Do While Len(f) > 0
With Workbooks.Open(wPath & f)
Application.Run "'" & .Name & "'!mYearChange.YearChangeFunction"
.Close True 'save
End With
n = n + 1
f = Dir()
Loop
MsgBox "End"
'snipped...
End Sub

VBA Macro to open/save/close workbooks in folder and subfolders

I have the following code that will open/save/close any/all workbooks in a folder. It works great, however, I also need it to include sub folders. The code needs to work without restrictions on the number of folders, sub folders and files, if possible.
I'm working with Excel 2010 and I'm new to VBA - would really appreciate any help!
Sub File_Loop_Example()
'Excel VBA code to loop through files in a folder with Excel VBA
Dim MyFolder As String, MyFile As String
'Opens a file dialog box for user to select a folder
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
MyFolder = .SelectedItems(1)
Err.Clear
End With
'stops screen updating, calculations, events, and statsu bar updates to help code run faster
'you'll be opening and closing many files so this will prevent your screen from displaying that
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'This section will loop through and open each file in the folder you selected
'and then close that file before opening the next file
MyFile = Dir(MyFolder & "\", vbReadOnly)
Do While MyFile <> ""
DoEvents
On Error GoTo 0
Workbooks.Open Filename:=MyFolder & "\" & MyFile, UpdateLinks:=False
ActiveWorkbook.Save
Workbooks(MyFile).Close SaveChanges:=True
MyFile = Dir
Loop
'turns settings back on that you turned off before looping folders
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True
Application.Calculation = xlCalculationManual
MsgBox "Done!"
End Sub
For anyone interested, I found an alternative which I managed to adapt and does exactly what I want:
Sub Loop_Example()
Dim MyFolder As String
Dim file As Variant, wb As Excel.Workbook
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
MyFolder = .SelectedItems(1)
Err.Clear
End With
Application.ScreenUpdating = False
For Each file In Filter(Split(CreateObject("WScript.Shell").Exec("CMD /C DIR """ & startFolder & "*.xl*"" /S /B /A:-D").StdOut.ReadAll, vbCrLf), ".")
Set wb = Workbooks.Open(file)
ActiveWorkbook.Save
wb.Close SaveChanges:=True
Set wb = Nothing
Next
Application.ScreenUpdating = True
MsgBox "Done!"
End Sub

Error while opening a file

I'm trying to open set of files from a specific folder. But while trying to open one of the files i get the attached Sign In pop-up.
email signin
I don't know how to get rid of this because we don't want someone to manually undo this, also, i'm cancelling the pop-up I get below pop-up
I just click No/Yes i get a Run time error.
But the designated file is open (Daily Testing Inventory file).
Here's my macro that I achieved so far:
Dim MyFolder As String
Dim MyFile As String
Application.ScreenUpdating = False
Application.EnableEvents = False
MyFolder = "C:\"
MyFile = Dir(MyFolder & "\*.xlsx")
Do While MyFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyFile
DoEvents
Loop
I'm a newbie as far as Excel VBA is concerned. (Since I don't have enough reputation can't post all the images)
You are not reading the next file name. hence the loop is infinite.
Please add the following line above "DoEvents":
MyFile = Dir()
Turn off Alerts as well
better synatx as well
use a Workbook object to hold the opened workbooks
do your code
close each Workbook (the code below does so without saving)
then trigger your next loop
code
Sub recut()
Dim MyFolder As String
Dim MyFile As String
Dim Wb As Workbook
With Application
.ScreenUpdating = False
.EnableEvents = False
.DisplayAlerts = False
End With
MyFolder = "C:\"
MyFile = Dir(MyFolder & "\*.xlsx")
Do While MyFile <> ""
Set Wb = Workbooks.Open(MyFolder & "\" & MyFile)
'do code
Wb.Close False
MyFile = Dir
Loop
With Application
.ScreenUpdating = True
.EnableEvents = True
.DisplayAlerts = True
End With
End Sub

How to avoid "A file named ... already exists in this location. Do you want to replace it?" prompt on subsequent save?

I save all worksheets in a workbook as individual CSV files.
If I make a change to any of the worksheets and run the macro again, it prompts me with the "A file named ... already exists in this location. Do you want to replace it?".
If I click Yes, the prompt comes up for every worksheet. If I click no, the macro throws an error.
Is there a way to avoid the prompt?
Sub CSVAutomation()
Dim ws As Worksheet, wb As Workbook
Dim pathh As Variant
Set wb = ActiveWorkbook
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
If .Show = -1 Then 'a folder was picked
pathh = .SelectedItems(1)
End If
End With
If pathh = False Then Exit Sub 'no folder picked; pathh is false
Application.ScreenUpdating = False
For Each ws In wb.Sheets(Array("01 - Currencies", ...."14 - User Defined
Fields"))
ws.Copy
With ActiveWorkbook
'Application.DisplayAlerts = False 'to avoid overwrite warnings
' pathh is a string (variant) of the path of the folder; does not
need pathh.Path
.SaveAs pathh & "\" & ws.Name, xlCSV
.Close SaveChanges:=False
End With
Next ws
Application.ScreenUpdating = True
End Sub
Check my comment and (as Portland Runner says) you could turn off some alerts
I used this
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.AutomationSecurity = msoAutomationSecurityForceDisable
Application.AskToUpdateLinks = False
Using a procedure to put inside and used every time to turn it of and another to turned on helpme a lot with all the alerts.
Sub Alerts(ScreenUpdate As Boolean, DisplayAlerts As Boolean, AutoSecurity As Boolean, AskToUpdate As Boolean)
Application.ScreenUpdating = ScreenUpdate
Application.DisplayAlerts = DisplayAlerts
Application.AutomationSecurity = IIf(AutoSecurity, msoAutomationSecurityForceDisable, msoAutomationSecurityByUI)
Application.AskToUpdateLinks = AskToUpdate
End Sub

Run VBA code on specific time

I found the following code on this web site "save Excel file as CSV" is there any way with help of you'll I can auto run this code on specific time (11:00 pm every night), and save file name as current date (hr2015-05-05), any help will be greatly appreciated. Thanks
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim Sourcewb As Workbook
Dim Destwb As Workbook
Dim TempFileName As String
With Application
.ScreenUpdating = False
.EnableEvents = False
.DisplayAlerts = False
End With
Set Sourcewb = ActiveWorkbook
TempFileName = Sourcewb.FullName + ".csv"
'Copy the sheet to a new workbook
ActiveSheet.Copy
Set Destwb = ActiveWorkbook
'Save the new workbook and close it
With Destwb
.SaveAs Filename:=TempFileName, FileFormat:=xlCSV, ConflictResolution:=xlLocalSessionChanges
.Close SaveChanges:=False
End With
With Application
.ScreenUpdating = True
.EnableEvents = True
.DisplayAlerts = True
End With
End Sub
Edit fixed tag issue
I would do this one of two ways.
One would be through windows task scheduler. Where you will set up a task to open Excel and run it that way. See http://www.mrexcel.com/forum/excel-questions/302970-task-scheduler-vbulletin-script-auto-open-excel.html
Or
Use the code
Application.OnTime TimeValue("23:00:00"), SUBNAMEHERE
Changing SUBNAMEHERE to the sub where the code is. Not sure if it will run the beforesave part through
EDIT added code to have filename
Change TempFileName = Sourcewb.FullName + ".csv" to be
TempFileName = Sourcewb.FullName & " hr" & format(now,"YYYY-MM-DD") & ".csv"

Resources