Is it possible to run a macro every day at a time? - excel

I need to know if it is possible to have a macro executed daily at 7:00 am.
Would this be done through a macro, or through some visual basic component?

The issue with the Workbook_Open() event is that if you still need to action on your workbook manually during the day, the macro will launch, which can be source of errors depending on what your macro does.
Alternatively, you can use the Windows Task Scheduler as mentionned above to run a VB Script that will run the macro in your workbook.
Set xlApp = CreateObject("Excel.Application")
xlApp.DisplayAlerts = False 'turn off alerts
xlApp.Application.Visible = False 'keeps Excel hidden
Set xlBook = xlApp.Workbooks.Open("C:\MyPath\MyWorkbook.xlsm", 0, False)
xlApp.Run "MACRO_NAME"
xlBook.Save
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
Just type your script within notepad and save as .vbs (and then have the Windows Task Scheduler to run you .vbs).

There are a couple ways that I know of to do this, neither of which are perfect.
The first is the Application.OnTime method in VBA (documentation here). This method will schedule another method to be run at a specific time. I haven't thoroughly testing this function, so I don't know if the schedule will be preserved across excel restarts or even workbook closures.
Another option is the Windows Task Scheduler(thanks Mistella). You can set up a basic task within the task scheduler to open a specific workbook in excel at a given time at a given interval and have the code you wish to be run within the Workbook's Open event. Within that event you could check the time. If the time is close enough to your designated task scheduler time you could perform the work you needed to do, save the workbook, and close it, all without user interaction.

Related

VBScript to Refresh Excel Data Connections (Trouble with Office 365)

I have a large Excel file that uses PowerPivot to connect to several external data sources. The Excel file is stored in a SharePoint folder. I would like to be able to refresh the connections automatically overnight. To do this, I am using Windows Task Scheduler to trigger a VBScript each day at 2AM.
Previously, I had the script run a macro within the workbook to refresh all. This worked successfully until my organization recently updated to Microsoft Office 365 ProPlus. I am now struggling with the new read-only default setting for SharePoint. Following the update, whenever I open an Excel file from SharePoint, I see a yellow bar reading "Read-Only: We opened this workbook read-only from the server. Edit Workbook". When working with files manually, this has to be clicked before changes can be saved. I tried to research the programmatic workaround for this and found the recommendation to use the method .LockServerFile.
To streamline the trouble-shooting, I have tried to move the entire action into the VBScript script, rather than running a macro within the workbook. My code is below.
When I watch the process, the yellow "Read-Only" bar appears to pop up immediately before the save. I can run the process once with no apparent errors, but if I then manually open the file, I don't see the option to "Edit Workbook". If I manually change the file, save, and then run the script again, I get the error 800A03EC.
It seems that somehow the script is failing to correctly "release" the lock on the server file after it finishes.
Is there a way to fix this?
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("[[The Sharepoint Path]]")
objExcel.Application.DisplayAlerts = False
objExcel.Application.Visible = True
objExcel.ActiveWorkbook.LockServerFile
objExcel.ActiveWorkbook.EnableConnections
objExcel.ActiveWorkbook.Sheets(1).Range("P2").Value = Date
objExcel.ActiveWorkbook.RefreshAll
objExcel.ActiveWorkbook.Save
objExcel.ActiveWorkbook.Close false
objExcel.Application.Quit
set objworkbook = Nothing
set objExcel = Nothing
WScript.Quit

External data does not load in excel when scheduled from scheduled task

The problem is I made a script that opens and refreshes data in my excel.
The data is external data from a PHD server I get this data with a plugin installed on excel.
All works fine untill I try to schedule the script with task scheduler. when I schedule it as "run only when user is logged on" it workes fine. but when I try to schedule it as " run wheter user is logged on or not" it does not update the data.
(it does open the excel and saves it but no changes in the data)
It is set on a VM that acts as a desktop and the updates need to be done even when i'm logged of.
The code of the script: (that works fine when i manualy launch it)
Dim oExcel
Set oExcel = CreateObject("Excel.Application") 'launch excel.
oExcel.Visible = True ' makes the aplication visible (if not set to true the data won't be updated)
oExcel.DisplayAlerts = False' disables all excel allerts.
oExcel.AskToUpdateLinks = False 'now excel will not ask you to update links.
oExcel.AlertBeforeOverwriting = False 'excel will not display an alert before overwriting data in a cell.
code for the plugin to update data
Dim addIn
addIn = COMAddIn
Dim automationObject
automationObject = Object
Set addIn = oExcel.COMAddIns("ExcelCompanion")
Set automationObject = addIn.Object
automationObject.UNIF_workbook_refresh
code to save and close excel
oWorkbook.RefreshAll 'refreshes the workbook
oWorkbook.Save 'saves the updated workoob
oWorkbook.Final = True 'makes the file read-only
oExcel.Quit 'exits excel
Set oWorkbook = Nothing ' destroy the object (minimises damage if the object goes out of scope)
Set oExcel = Nothing ' destroy the object (minimises damage if the object goes out of scope)
these 3 block of code form the script.
Hencky!
Which version of Windows do you have? I had the same problem about a week ago, and I came across a very strange solution... :)
Try adding a folder into C:\Windows\SysWOW64\config\systemprofile, simply named "Desktop"... If you run a 32-bit version of Windows, do the same thing except the path must contain system32 instead of SysWOW64...
The "run wheter user is logged on or not" will now do the work... If you had a logging function in your script, you would've seen that the script stops somewhere arround Excel commands... I don't know why is that so, it simply is...

Windows Task Manager Schedule VBA Macro to Send An Email Using OutLook Daily Running Manually and Not Automatically

I have my macro which is running, & for this I created a vb script and used windows task manager to schedule its run every day.
Whenever I run manually or attempt changing the time in the trigger, I always make sure that both excel and outlook are not running.
If I run the macro in Excel VBA, it sends the email.
After scheduling the task to run everyday, just as a test if I go to (in TaskScheduler) View -> Hidden Tasks and manually click Run, it sends the email.
However, if I schedule it to run at a specific time everyday, say maybe starting today, 15 minutes from now, it does not send the email & the last run result is (0x0).
I have enabled all macros in the trust center settings and selected 'Trust access to the VBA project object model', & it's not an issue about administrator privileges.
This is my VB script
Dim ObjExcel, ObjWB
Set ObjExcel = CreateObject("Excel.Application")
Set ObjWB = ObjExcel.Workbooks.Open("C:\Users\myUser\MyLocation\MyFile.xlsm")
ObjExcel.Visible = False
ObjExcel.DisplayAlerts = False
ObjExcel.AskToUpdateLinks = False
ObjExcel.AlertBeforeOverwriting = False
'vbs opens a file specified by the path below
'either use the Workbook Open event (if macros are enabled), or Application.Run
ObjExcel.Application.Run "MyFile.xlsm!main_macro"
ObjWB.Save
ObjWB.ActiveWorkbook.Close
ObjExcel.Quit
Set ObjWB = Nothing
Set ObjExcel = Nothing
WScript.Echo "Finished."
WScript.Quit
Also, here are my TaskScheduler Settings:
Ref:
Sending email from excel automatically based on date
How to set recurring schedule for xlsm file using Windows Task Scheduler
How can you run an Excel macro through a schedule task
Task Scheduler does not run Excel VBA Code to send PDF as Email Attachment
If I set the below to True:
ObjExcel.Visible = False
ObjExcel.DisplayAlerts = False
ObjExcel.AskToUpdateLinks = False
ObjExcel.AlertBeforeOverwriting = False
Excel opens in read-only mode and says click notify to receive the notification that you can now edit the workbook but I cannot edit it, says another user has the workbook open for editing.
I think the point is that the line
ObjWB.ActiveWorkbook.Close
must be
ObjWB.Close
.
Please try this and comment your results.

VBS Start an instance of excel then detach from it

So I basically have a VBS script that's supposed to post data to an Excel sheet asynchronously. I currently do this by using GetObject on the workbook's path like so:
Set xlBook = GetObject(strPath & "\Runner.xlsm")
This seems to work fine, except that the workbook will close at the end of the script if it was not open previously (not desired, I have a macro that will close and save the book when necessary).
This is similar to Question 7708039, EXCEPT I want to intentionally keep the excel instance OPEN, not force it to close (the reverse of his problem).
I think it's closing because the variables referencing the object get destroyed at the end of the script, but I can't figure out how to release those handles without destroying them (i.e. set to Nothing).
Instead of getting a reference to a specific workbook, have you tried getting a reference to Excel and then opening the workbook?
' 1a. Get an existing Excel instance...
Set Excel = GetObject(, "Excel.Application")
' 1b. Or, create one. Make it visible for testing.
Set Excel = CreateObject("Excel.Application")
Excel.Visible = True
' Load the workbook...
Set Workbook = Excel.Workbooks.Open(strPath & "\Runner.xlsm")
' Do stuff and save, if desired.
' Close workbook...
Workbook.Close
' Excel stays open. If you want to close Excel, use:
Excel.Quit
Per phd443322's two comments Comment 1 and Comment 2, this is apparently by design.
The solution here is to trick the object (in this case Excel) into thinking the user will need to interact with it or maintain interaction after the reference is destroyed.
Thus, the proper workaround is to make it interactive, in this case using:
xlApp.Visible = True
Thus Excel becomes visible and won't close just because the reference is destroyed.
Since I don't want this instance of Excel visible, I then have the VBS use xlApp.OnTime to call a macro (after one second, plenty of time for the VBS script to have exited) to hide the application window again.
This makes the application blink up on the screen for a second, but it's the best I can do in this instance.
I had the same problem using
xlApp.Visible = True
with this call on windows
wscript my-script.vbs C:/path/to/file.xml
But when I changed the separator from / to \ it worked:
wscript my-script.vbs C:\path\to\file.xml

VB script unable to access file

I am trying to schedule a vba script. I am working through the company server and am wondering if I can not access this due to administrative restrictions? here is the code:
Dim xlApp
Dim xlBook
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("\\Computer\denfs1\data\1EpUSRgltry\Permitting - Wells & Sundries\WEST (CO-MT-ND)\Schedules & Status\Planning and Permiting Spread sheet(West) Permit and Planning spread sheet.xlsm", 0, True)
xlApp.Run "Click"
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
Here is the error I am getting
What does the macro "Click" do? If it make changes, close it without saving (change to True if you want to save changes by the Click macro).
xlBook.Close False
You may also want to debug from Excel by putting xlApp.Visible = True before opening the .xlsm workbook.
There might be a hidden Excel.exe locking that same file from previous script execution (say you press Ctrl-C before the macro "Click" finishes). Close all visible Excel windows and ensure there are no Excel.exe running in task manager.
If you keep pressing Cancel when Excel asks you to save changes to it, it will stuck in background even the vbs did not pick up any error.
The problem was a syntax error with the name of the file... Make sure you have the whole string accurate :/

Resources