Windows Task Scheduler to Run batch file that calls vbscript that runs a macro - excel

I have a batch file that first runs a vbscript to open excel and run a macro. Then it chains 2 other batch files to complete the process. Everything works if I simply double-click on the first batch file and let it run.
When I try to create a windows task scheduler to run the first batch file, it says it completed successfully, but the results of the macro and the other 2 batch files do not get ran/outputted.
First batch file:
REM #ECHO OFF
cscript //nologo "C:\Program Files (x86)\salesforce.com\Data Loader\conf\SaveToCSV.vbs"
Call "C:\Program Files (x86)\salesforce.com\Data Loader\conf\SFDL2.bat"
Call "C:\Program Files (x86)\salesforce.com\Data Loader\conf\SFDL3.bat"
QUIT
.vbs file:
Option Explicit
Dim xlApp, xlBook
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\Program Files (x86)\salesforce.com\Data Loader\conf\VendorManagementReport-Import2.xlsm", 0, True)
xlApp.Run "CopyToCSV"
xlBook.Close False
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
WScript.Quit
I don't think the other 2 batch files are relevant as it never actually creates the .csv file from the .xlsm workbook, which is the first step.

Try removing the Call from the first batch file, to start the other two in the same context
REM #ECHO OFF
cscript //nologo "C:\Program Files (x86)\salesforce.com\Data Loader\conf\SaveToCSV.vbs"
"C:\Program Files (x86)\salesforce.com\Data Loader\conf\SFDL2.bat"
"C:\Program Files (x86)\salesforce.com\Data Loader\conf\SFDL3.bat"
QUIT

Related

Why does the execution of a Python script fail on running it with a batch file with the Windows Task Scheduler which uses vir env?

I have a Python script on my Windows machine which has to be run in a virtual environment in order to satisfy package dependencies.
I have created a batch file to use it with Task Scheduler which looks like the following:
call activate vir_env
python "C:\Users\xxx\Documents\Anaconda\envs\vir_env\Scripts\script.py"
call conda deactivate
pause
set /p id="Press enter when finished"
This batch file executes successfully when I run it by manually double clicking on it. But it is failing after a period of execution when I schedule it for execution by the Task Scheduler. (I am saving this batch file on my desktop and pointing the scheduler to read it from there.)
I also see the following line on cmd while running it manually.
DevTools listening on ws://127.0.0.1:61347/devtools/browser/d86ec8f2-7af2-4a2b-89f4-6c6f7025cc02
But I get the following notification if I schedule and run it with Task Scheduler:
DevTools listening on ws://127.0.0.1:55329/devtools/browser/e8cd5010-6b41-4d35-a465-78a75e87a547
That can be seen in the error output as posted below.
DevTools listening on ws://127.0.0.1:55329/devtools/browser/e8cd5010-6b41-4d35-a465-78a75e87a547
Traceback (most recent call last):
File "C:\Users\xxx\Documents\Anaconda\envs\vir_env\Scripts\script.py", line 432, in <module>
gv.save(deps, buffer, fmt='png')
File "C:\Users\xxx\Documents\Anaconda\envs\vir_env\lib\site-packages\holoviews\util\__init_.py", line 820, in save
return renderer_obj.save(obj, filename, fmt=fmt, resources=resources,
File "C:\Users\xxx\Documents\Anaconda\envs\vir_env\lib\site-packages\holoviews\plotting\renderer.py", line 627, in save
rendered = self_or_cls(plot, fmt)
File "C:\Users\xxx\Documents\Anaconda\envs\vir_env\lib\site-packages\holoviews\plotting\renderer.py", line 201 in __call__
data = self._figure_data(plot, fmt, **kwargs)
File "C:\Users\xxx\Documents\Anaconda\envs\vir_env\lib\site-packages\holoviews\plotting\bokeh\renderer.py", line 131, in _figure_data
img = get_screenshot_as_png(plot.state, driver=state.webdriver)
File "C:\Users\xxx\Documents\Anaconda\envs\vir_env\lib\site-packages\bokeh\io\export.py", line 223, in get_screenshot_as_png
web_driver.maximize_window()
File "C:\Users\xxx\Documents\Anaconda\envs\vir_env\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 737, in maximize_window
self.execute(command, params)
File "C:\Users\xxx\Documents\Anaconda\envs\vir_env\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\xxx\Documents\Anaconda\envs\vir_env\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.comnon.exceptions.NoSuchWindowException: Message: Browsing context has been discarded
How can this be possible?
The dev tool link seems to be different in the two cases.
Could this be the potential cause of the issue?
I had the same problem but found a solution without using task scheduler
Create a file and name it eg Example.bat
Edit the file and paste this code
set Path_To_File=C:\Path\To\File
set SunDay_Time=11:34
set MonDay_Time=13:20
set TuesDay_Time=07:30
set WednesDay_Time=02:57
set ThursDay_Time=11:42
set Friday_Time=23:59
set Saturday_Time=23:59
#echo off
:loop
timeout 10
for /f %%i in ('powershell ^(get-date^).DayOfWeek') do set day=%%i
SET "HH=%TIME:~0,2%
SET "MM=%TIME:~3,2%
if %day%==Sunday set Time_Run=%SunDay_Time%
if %day%==Monday set Time_Run=%MonDay_Time%
if %day%==Tuesday set Time_Run=%TuesDay_Time%
if %day%==Wednesday set Time_Run=%WednesDay_Time%
if %day%==Thursday set Time_Run=%ThursDay_Time%
if %day%==Friday set Time_Run=%Friday_Time%
if %day%==Saturday set Time_Run=%Saturday_Time%
if "%HH%:%MM%" EQU "%Time_Run%" start "%Path_To_File%"
goto loop
Edit this section
Modify the path name of the program you want to run at the specified time, and modify the time you want to run the program through this section, and then save the file
set Path_To_File=C:\Path\To\File
set SunDay_Time=11:34
set MonDay_Time=13:20
set TuesDay_Time=07:30
set WednesDay_Time=02:57
set ThursDay_Time=11:42
set Friday_Time=23:59
set Saturday_Time=23:59
Press Windows and R and type shell:startup
Create a file and name it example.vbs
Edit the file and paste this code
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\Path\To\File.bat" & Chr(34), 0
Set WshShell = Nothing
Replace C:\Path\To\File.bat with the path of the batch file and save the file

Batch file to open 3 programs and a folder - I'm almost there

Batch file Requirement;
I need to open 1) WindSailor 2) Addons Linker 3) folder (drive) "O" and 4) Excel-01. MSFS.xlsm.
The issue is - when Excel opens, it is not set to autosave via OneDrive. I have to set it to autosave manually after it opens.
I have 1 .bat file that opens 1, 2 and 3 perfectly.
#echo off
start "" "C:\Users\Dad\Desktop\WindSailor"
start "" "C:\Users\Dad\Desktop\Addons Linker"
start "" "O:\"
And I have a second .bat file that opens Excel perfectly - all set for autosave via OneDrive.
#echo off
set params=%*
start excel "E:\OneDrive\03. Excel\02. Flight Sim\01. MSFS\01. MSFS.xlsm" /e/%params%
But when I combine the two, Excel opens but not set to autosave...
#echo off
start "" "C:\Users\Dad\Desktop\WindSailor"
start "" "C:\Users\Dad\Desktop\Addons Linker"
start "" "O:\"
set params=%*
start excel "E:\OneDrive\03. Excel\02. Flight Sim\01. MSFS\01. MSFS.xlsm" /e/%params%
I have tried countless variations - what am I missing ?

Excel VBA Workbook_Open does not work when Excel is already open

I was trying to automate VBA run with its file opening from command line as below:
cmd.exe /C set MacroName=MyMacro \& EXCEL.EXE C:\\_documents\\Book2.xlsm
The VBA scripts and files are as follows:
Book2.xlsm/Module1
Sub MyMacro()
MsgBox "MyMacro is running..."
End Sub
Book2.xlsm/ThisWorkbook
Private Sub Workbook_Open()
Dim strMacroName As String
strMacroName = CreateObject("WScript.Shell").Environment("process").Item("MacroName")
If strMacroName <> "" Then Run strMacroName
End Sub
Now, the above cmd command does work, expectedly notifies me with the MsgBox, when Excel is not open. But it does not work when Excel is already being open with other project/file(s).
How can I make this work?
The problem was that when you launch an Excel file in the already open Excel instance passing environment variables through cmd.exe or command line does not work correctly for some reason, rather than as a VBA-side problem.

Vba Shell call works with some programs but does not work with others

Shell call works with some programs that I have but does not work with others. I am putting the most basic call here for opening an exe without any further commands
Shell "C:\Program Files\qBittorrent\qbittorrent.exe", 1 'works
Shell "C:\Program Files\AmiBroker\Broker.exe", 1 'works
Shell "C:\Program Files\CTrading\QuantShare\QuantShare.exe", 1 'Run-time error '5': Invalid procedure call or argument
Shell "C:\Program Files (x86)\Equis\MetaStock\MsWin.exe", 1 'same error
I am on the verge of giving up unless I meet a savior here!!
System: Windows 10 Pro Version 1909 OS Build 18363.476
Microsoft Excel 2013 64-bit
A bit of an ugly fix, but it might help:
Shell "cmd /c ""C:\Program Files\CTrading\QuantShare\QuantShare.exe""", 1
I don't have any of the programs you are having problems with, so it is a bit of a guess. If this doesn't help, the next step is cmd /c start ...
Finally, i could use ShellExecute as follows:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Target, Range("A1:A2000")) Is Nothing Then
Set objShell = CreateObject("Shell.Application")
para = "TaskManager ChangeSymbol newsymbol:" & ActiveCell.Value
objShell.ShellExecute "C:\Program Files\CTrading\QuantShare\QuantShare.exe", para, "", "open", 1
Set objShell = Nothing
Cancel = True
End If
End Sub
Can I make ShellExecute not to open a new instance of the program and rather activate the currently open instance and pass the arguments (similar to Shell call? Also how to make ShellExecute not take focus? I want the focus to stay back in Excel.

Batch script to change many .xlsx files to .csv

I have a folder with many subfolders (1000+) and inside the subfolders are a few excel files, in .xlsx format. I want to run a batch script from the main folder, which goes into each sub folder and changes each .xlsx Excel file into a .csv Excel file.
The formatting of the file system:
MainFolder
---subfolder1
----->file1.xlsx
---subfolder2
----->file2.xlsx
etc.
From this thread: Convert XLS to CSV on command line, I figured out that I can't just rename each .xlsx to .csv, so I made the ExceltoCSV.vbs file (the modified ScottF answer, second one down). My understanding is that I can make a for loop in a batch file to run ExceltoCSV.vbs for each sub folder. The following line of code is something i attempted, but it didn't work. It usually says *.xlsx file is not found.
for /R %%F in ("C:\MainFolder") do cscript ExceltoCSV.vbs *.xlsx *.csv
Also tried this:
for /d /r "C:\MainFolder" %%F in (.) do cscript ExceltoCSV.vbs "%%F\*.xlsx" *.csv
Error message:
C:\MainFolder\ExceltoCSV.vbs(17,1) Microsoft Excel: 'C:\MainFolder\folder1\*.xlsx' could not be found. Check the spelling of the file name, and verify that the file location is correct.
The VBS script you got from SO only takes a string as an input. What you'll need to do is create a loop with a regex pattern that builds those file names dynamically and then run the script with an input string representing each file name. Pseudo code:
for loop (iterate over file names in dir){
set $file_name=$iterated_file_name_from_loop
ExceltoCSV.vbs "$file_name.xlsx" *.csv
}

Resources