Task Scheduler does not Run the Task - excel

As the title says, I am trying to get the Task Scheduler to do as follows:
Open an specific Excel file at an specific time every day and run the module 1 within said file.
The workbook name is Daily Invoiced, and it contains a Macro, therefore the file is an xlms. The code I need to run is in the Module 1, therefore this is the one that needs to be selected.
This file is stored in my folder C:\Users\MartiJor1\Documents\MACROS\Daily Invoiced.
What have I done so far?
Followed the example listed in https://www.thespreadsheetguru.com/blog/how-to-automatically-run-excel-vba-macros-daily where the plan is to use a Script. Here is what mine ends looking like:
'Input Excel File's Full Path
ExcelFilePath = "C:\Users\MartiJor1\Documents\MACROS\Daily Invoiced ZAMSOTC02 LAC TEAM.xlsm"
'Input Module/Macro name within the Excel File
MacroPath = "Module1.LAC_Daily_Invoiced_Report"
'Create an instance of Excel
Set ExcelApp = CreateObject("Excel.Application")
'Do you want this Excel instance to be visible?
ExcelApp.Visible = True 'or "False"
'Prevent any App Launch Alerts (ie Update External Links)
ExcelApp.DisplayAlerts = False
'Open Excel File
Set wb = ExcelApp.Workbooks.Open(ExcelFilePath)
'Execute Macro Code
ExcelApp.Run MacroPath
'Save Excel File (if applicable)
wb.Save
'Reset Display Alerts Before Closing
ExcelApp.DisplayAlerts = True
- Note: If I execute the script with the Windows Based Script Host, it runs smoothly.
I also used the rest of the configuration suggested in the article for the script to run, except I am using Windows 10 Pro. However, nothing happens at the scheduled hour, nor when I run it manually. On the Last Run Result I can see the code (0x41303) which is an error code related to a date in the past. Does not matter how many times I amend it for the near future, it does not run.
I can not see the error. I believe it must be somewhere in the Actions Tab, and I arrive to this conclusion by the fact that I can run the Script with the Windows Based Script Host as mentioned above. Any idea guys?
Here is also the script from the Task when I export it:
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>2020-10-31T21:41:26.1715916</Date>
<Author>GUWW\MartiJor1</Author>
<Description>Test</Description>
<URI>\DailyInvoiced</URI>
</RegistrationInfo>
<Triggers>
<CalendarTrigger>
<StartBoundary>2020-11-02T14:03:00</StartBoundary>
<Enabled>true</Enabled>
<ScheduleByDay>
<DaysInterval>1</DaysInterval>
</ScheduleByDay>
</CalendarTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<UserId>S-1-12-1-4092016482-1174842289-577708437-4023581491</UserId>
<LogonType>Password</LogonType>
<RunLevel>LeastPrivilege</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>Parallel</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
<AllowHardTerminate>false</AllowHardTerminate>
<StartWhenAvailable>true</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>false</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>
<WakeToRun>true</WakeToRun>
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
<Priority>7</Priority>
<RestartOnFailure>
<Interval>PT1M</Interval>
<Count>3</Count>
</RestartOnFailure>
</Settings>
<Actions Context="Author">
<Exec>
<Command>"C:\Windows\System32\cscript.exe"</Command>
<Arguments>"C:\Users\MartiJor1\Documents\MACROS\Daily.vbs"</Arguments>
</Exec>
</Actions>
</Task>
Thanks in advance.

Related

Apply MS Project SetTaskMode via Excel VBA

I am reading a sheet in Excel and creating a Microsoft Project Plan of tasks, Work, Notes, etc.
The code is being executed out of MS Excel.
How can I get the Active.Project to assign, SetTaskMode Manual:= False?
I receive an error, please note Application.Visible = True.
As far as .Application.Methods (Project) go, I am able to invoke the Application.About screen, i.e on Sub execution the MS Project About screen opens up, however after that line, it stops.
Basically, I would like to set the Active Sheet Task Mode to be set to 'automatically scheduled' as the default for all tasks as they are being imported.
The project property in question is NewTasksCreatedAsManual and is used like this to make all new tasks auto-scheduled:
ActiveProject.NewTasksCreatedAsManual = False
Alternatively, to set the task mode to auto-schedule on an individual task, use the Manual property like this:
tsk.Manual = False
' or to change to manually scheduled
tsk.Manual = True

Why isn't my script able to locate my excel file when given correct filepath?

I have a .vbs script that opens two excel files and copies the contents of a sheet from the first file into the second file. It's supposed to run daily via task scheduler.
The script ran normally until the excel files in question were recently modified and slightly renamed - I went through the script and edited the filenames accordingly after the changes were made, triple checking that the names and filepaths matched up.
Everything ran fine for a few weeks after the changes but now the script fails immediately after starting, giving me an error claiming that the file can't be located even though the file is located at the given path. The error code is 800A03EC.
This is the first chunk of code in the script, including line 7 which seems to be throwing the error:
Dim objApp ' as excel object
Dim x, y ' as workbook
Set objApp = CreateObject("Excel.Application")
objApp.DisplayAlerts = False
objApp.Visible = False
Set x = objApp.Workbooks.Open("S:\Work (Public)\PORT MGMT & TRADING\PORT MGMT FORMS\ORION_FPFOCUS.xlsm")
Set y = objApp.Workbooks.Open("S:\Work (Public)\PORT MGMT & TRADING\PORT MGMT FORMS\FPFocusPasteSpecialValues.xlsb")
Dim WSx, WSy ' as excel worksheet
Set WSx = x.Worksheets("FPSUP")
Set WSy = y.Worksheets("FPFOCUS-COPY")
WSy.Range("B1").value = FormatDateTime(Now)
objApp.Application.Run "ORION_FPFOCUS.xlsm!Auto_Open"
The excel files in question are both located in the same directory:
S:\Work (Public)\PORT MGMT & TRADING\PORT MGMT FORMS\ORION_FPFOCUS.xlsm
S:\Work (Public)\PORT MGMT & TRADING\PORT MGMT FORMS\FPFocusPasteSpecialValues.xlsb
And the script is located here:
C:\Users\bserv\Documents\CopyFPFocus.vbs
The S drive isn't a physical drive, it's a virtual drive hosted by a service called Workplace. I can navigate through it and open the excel files manually just fine.
I initially thought it was a user privilege issue with task scheduler, but I've selected the 'run with highest privileges' option and the script is still failing. I also went through the privacy/trust settings in Excel to make sure the script wasn't being denied access, but I don't see any settings that would disable the script from working, and I also know that all these settings haven't changed since the script was working, so I don't see how they could be potential causes.
When I try running the code manually via cscript in the command line, it returns this error:
C:\Users\bserv\Documents\CopyFPFocus.vbs(25, 4) (null): The remote procedure call failed.
This is line 25 of the script for reference:
objApp.Run "RefreshAllStaticData"
When I try again by running command prompt as an admin, I get the same error I got initially. Sorry, is it possible the file was moved renamed or deleted.
The part that really confuses me is that the script ran fine for some time after the changes - so I'm really unsure about what actually changed to cause this issue to randomly pop up.
One other thing I've noticed is that upon opening the excel files I get a popup saying they're in use and locked for editing by me. I can't remember if this popup was showing up before the issue started. The other users on the network have been accessing these files regularly long before the script started failing, so I don't see how that could be the issue. The error code/message also doesn't seem to correspond with this being the problem.
I'd appreciate any help or insight into this issue. Thank you!

Executing VB script from Spring Boot Application

I want to execute a VB script from Spring Boot application, the script is like:
' Creating a file as test acces to macro
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.CreateTextFile("C:\excel\FLAG_TEST")
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\excel\excelFile.xls")
objExcel.Application.EnableEvents = False
objExcel.Application.DisplayAlerts = False
objExcel.Application.Run "excelFile.xls!executeMacroFunction"
objExcel.Application.Quit
I tried to execute the script from Spring Boot service by:
Runtime.getRuntime().exec(new String[]{"C:\\Windows\\System32\\wscript.exe", "C:/vb/script.vbs"});
The above line code does not work on the application deployed on Tomcat 9 (it works fine when running as Spring Boot App on Eclipse)
Then I tried to execute the script via a batch file launched from the app
On batch file, I tried to execute the VB script by
rem First way
Set wscript = CreateObject("WScript.Shell")
wscript.Run "C:/vb/script.vbs"
--------------------
rem Second way (System 64bit)
C:\Windows\System32\wscript.exe C:/vb/script.vbs
--------------------
rem Third way (System 64bit)
wscript C:/vb/script.vbs
And running the batch file from Java with different ways too:
// First way
ProcessBuilder processBuilder = new ProcessBuilder("C:/batch/executor.bat");
final Process process = processBuilder.start();
// Second way
Process process = Runtime.getRuntime().exec("cmd /c start \"\" C:/batch/executor.bat");
// Third way
Process process = Runtime.getRuntime().exec(
"cmd /c start \"\" C:/batch/executor.bat",
null,
new File("C:\\Windows\\SysWOW64"));
All these ways do not work, the scripts have no problem since they work when I run manually the batch file (by double click)
On the execution of the macro from Spring Boot, the test file (FLAG_TEST) is created and then the execution is blocked at the line:
Set objExcel = CreateObject("Excel.Application")
Am I missing something ?...Thanks a lot in advance !
Tried also with Jacob DLL to run the Macro inside the excel file, it also didn't work for me within a Tomcat server
I decided at the end to abandon any kind of external tool and do the thing within Spring Boot, parsing the Excel file via an Excel Java API and migrating the Macro program to Java: JExcel
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
Unlike some other Excel parsing APIs, the Jexcel get the cell text as it is: String, Number, Boolean, Formula (its displayed result), no need to handle the different cases of content type
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.WorkbookSettings;
// Set Encoding 1252 that supports many European languages (special characters included)
WorkbookSettings workbookSettings = new WorkbookSettings();
workbookSettings.setEncoding("Cp1252");
Workbook workbook = Workbook.getWorkbook(new File(EXCEL_FILE_LOCATION), workbookSettings);
Sheet sheet = workbook.getSheet(0);
Cell cellDemo = sheet.getCell(0, 0); // Or sheet.getCell("A1");
// Get the displayed cell centent as a text
String cellContent = cellDemo.getContents();
System.out.print("Cell A1 centent:" + cellContent);
The Java parsing makes the exception handling of data validation easier and more precise, no kind of abstract HMI error message (Error occurred wile processing the Excel file...)
Turns out that the Excel Java reading API implementation took less time than the several attempts of runing the Macro externally :D

Run VBA Excel macro once a day

I have some Excel macro which works on a specific Excel worksheet. It checks some table and sends reminder email to some people as needed.
I want that this macro will run once a day in order to check the table every day so I will not need to open the worksheet and to do it myself every day.Does it availabe to do it? I heard about Windows task scheduler as one option, Do you think that is a good option for my purpose?
Task Scheduler is a good option as you say. To spawn a new process and open a workbook you'd have a command line specifiying (1) The Excel executable and (2) the workbook to open so something like
C:\Program Files\Microsoft Office 15\root\office15\Excel.exe "c:\MyWorkbook.xlsm"
I'd advise double quotes around the full path to the workbook (but not required for the Excel.exe).
Then in MyWorkbook.xlsm you can write code that runs upon workbook opening, classically this has been sub Auto_Open in any standard module or Sub Workbook_Open() in the ThisWorkbook module.
I would recommend a VBScript file and make that to run every day using task scheduler. I prefer this, cause then I can open the Excel file any time of the day and the macro won't run (in case you just want it to update only at that specific time).
This is the VBscript you need to write in notepad and then save with *.vbs extension.
Option Explicit
'On Error Resume Next 'Comment-out for debugging
ExcelMacro
Sub ExcelMacro()
Dim xlApp
Dim xlBook
Set xlApp = CreateObject("Excel.Application")
Set xlBook =
xlApp.Workbooks.Open("path\to\the\file.xlsm", 0, True)
xlApp.Run "Update" 'Name of your Sub
xlBook.Save
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
Then you can set the event scheduler from the command-line, like this from here:
schtasks /Create [/S <system> [/U <username> [/P [<password>]]]]
[/RU <username> [/RP <password>]] /SC <schedule> [/MO <modifier>] [/D <day>]
[/M <months>] [/I <idletime>] /TN <taskname> /TR <taskrun> [/ST <starttime>]
[/RI <interval>] [ {/ET <endtime> | /DU <duration>} [/K] [/XML <xmlfile>] [/V1]]
[/SD <startdate>] [/ED <enddate>] [/IT] [/Z] [/F]
Other links you may find useful:
Task Scheduler from the command line? from SuperUser
What is a simple way to schedule a single event to happen at some time in the future? from Linux & Unix
How to Schedule Programs to Run Automatically in Windows 7? from Gizmo's freeware (TechSupportAlert)

Task Breaking: Microsoft Windows 2012R2, Task Scheduler, Excel 2013 VBScript

I am trying to move some Excel automation Tasks (Task Scheduler) from an older (Win2003) server to a new Windows 2012 R2 server.
I can get it to work when I first create the task, but if I change anything it stops working and I can't figure out why, or how to stop it from changing. Any thoughts? (also see my second observation below)
Here's What Happens
I create the initial task as shown below and it works fine, but if I change the user that the script runs as, It fails with the error:
Cannot run the macro 'Build'. The macro may not be available in this workbook or all macros may be disabled.
Changing the task to run as the original (working) user does not fix it. I get the same error when I re-run the task and have to delete/re-create it to get it to run again.
File/Task Details
D:\ApplicationDir\run.wsf (simplified)
<job id="1">
<script language="VBScript">
On Error Resume Next
Dim excel
Dim SourceFile
Set excel = CreateObject("Excel.Application")
SourceFile = "D:\ApplicationDir\File.xlsm"
excel.Workbooks.Open SourceFile
excel.Run "Build"
excel.Workbooks.Close
If Err <> 0 Then
... write Err.Description to file ...
End If
Set excel = Nothing
</script>
</job>
Task (in Task Scheduler)
- Runs as a user Account
- Run whether user is logged on or not
- Run with highest privileges
- Configure For: Windows Server 2003, Windows XP or Windows 2000
Triggers:
- Daily At 6:15 AM every day
Actions:
- Start a Program:
- Program: C:\Windows\System32\cscript.exe
- Arguments: run.wsf
- Start In: D:\Application_Dir\
Another Observation
If I select any other "Configure for:" option, I lose the ability to select "Windows Server 2003, Windows XP or Windows 2000" altogether. The option just isn't there when I go back to edit the task properties. Any ideas why this is happening ?
Thanks in advance.

Resources