Home » excel » Using Excel vba Macro to be run through Windows Schedule Task

Using Excel vba Macro to be run through Windows Schedule Task

Posted by: admin March 9, 2020 Leave a comment

Questions:

I have a Excel spreadsheet which I’ve set up a timer to run code into a database. If the spreadsheet is open and the time now is the time set within the timeslot then it exports the data into the database

I use this line in both my subroutine and the workbook_open Application.OnTime TimeValue("22:00:00"), "ExportOpenJobs"

This is great for when the spreadsheet is open, but I want to be able to set it through the Windows Schedule task.

I’m using Windows Server 2012 as my host pc and where the file is stored. Within the Task Scheduler I set the Action to Start a program and the Program script to the location and the actual *.xlsm file along with the start time for the Task. I set this task 30seconds before the time within the Excel VBA.

My problem is that the Windows Task Scheduler runs at the time set, after looking at the Task History I can see the Task Started/Completed and Action Started/Completed often taking around 50mins to complete, but when I check the database the Excel VBA hasn’t run.

How can I get my Task Scheduler to run the Excel VBA code?

Within the Windows Server do you actually need to have Excel installed, therefore should it be done on another machine?

How to&Answers:

Hello what I would do is create this .VBS file and then use Windows Task Scheduler to execute this vbs file at the desired interval.

Set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")

Set myxlApplication = CreateObject("Excel.Application")
myxlApplication.Visible = False
Set myWorkBook = myxlApplication.Workbooks.Open( curDir & "\myTest.xlsm" ) 'Change to the actual workbook that has the Macro
myWorkBook.Application.Run "Module1.HelloWorld" 'Change to the Module and Macro that contains your macro
myxlApplication.Quit

Application.Run Method (Excel)

This example does require Excel to be installed on to the host running the scheduled task. If that host is a Server or a Desktop computer is your choice.

The Windows Task Scheduler should be done as such for the Action portion of the task:

Action: Start a program

Program/script: C:\Windows\SysWOW64\cscript.exe

Add arguments (optional): C:\Path_to_your_vbs\Your.vbs

Start in (optional): C:\Path_to_your_vbs\

Answer:

In Windows Task Scheduler set:
Action: Start a Program
Program Script: The Excel.exe with path in full quotes.
Add Arguments: The workbook you want to open with full path in quotes

Check out this link: https://answers.microsoft.com/en-us/windows/forum/windows_8-performance/excel-files-can-not-be-opened-in-task-scheduler-in/aa6cf065-09ac-44d8-b6fb-a2f2ecd9b8cc

Worked for me after banging my head for a couple hours.