VBA - Execute or Run .bat File Inside Macro - vba

I have been attempting to automate a series of administrative events for some of the users where I work by creating scripts and macro's and so on..
These scripts and macros work great, however, I would like to make a the process even easier for the users by running a single batch file that will systematically execute the scripts and macros.
The batch file I currently have, calls all the scripts one by one, and the very last script opens one of the xlsm workbooks which contains a few macro's in it - and here is where the issue is - There are still scripts to be executed but they can only be executed once this workbook has executed all its macros.
So my initial thought was to test if the workbook is open, if it is, delay the execution of the next script by a minute or so, then test again and again... until it is closed.. Then I thought perhaps it would be easier to execute the next set of scripts (also in a batch file) from within a macro.
So, I have this code:
Sub Run_BAT()
Set obj = CreateObject("Wscript.Shell")
obj.Run Chr(34) & "X:\Test\" & "Termination Reports Scripts\" & "Execute_Terminations.bat" & Chr(34), 0, True
Set obj = Nothing
End Sub
Which gives me an error:
Permission Denied
Then there's this code:
Sub WriteAndRunBatFile()
Call Shell("X:\Test\Termination Reports Scripts\Execute_Terminations.bat")
End Sub
Which gives me the error:
Invalid procedure call
Any and every single code sample that contains the "Shell" command gives this error.

Place your path to bat file in quotes:
Call Shell("cmd /c ""S:/somebatfile.bat""", vbNormalFocus)

Or
Call Shell("cmd.exe /C /K " & "ChDir X:\Test\Termination_Reports_Scripts && Execute_Terminations.bat", vbNormalFocus)
And yes, check permissions.

My theory is you're missing a reference in your application to the Windows Script Host Object Model.
In the VBA Editor, go to Tools, References, make sure that one's ticked.
It's not ticked by default for security reasons - imagine unintended access to the command prompt in every instance of a Microsoft Office application...!

(1) Check permission of user of that X directory.
(2) Test the code by removing spaces from directory name.
Also try the following code (Please try it by removing spaces from directory name).
Sub Button1_Click()
Call Shell("CMD.EXE /C " & "X:\Test\Termination_Reports_Scripts\Execute_Terminations.bat")
End Sub

Related

Shell hitting Run-Time error '5' trying to call R script in Access VBA

I made a simplified version of my code that directly highlights the issue.
I have read dozens of similar issues/solution.
Part of my workflow in VBA in Microsoft Access involves calling an R script that does some logic and returns information to a table in the same database.
It was working until we moved the location of the R installation to a new drive. Changing the path to this new install location does not work. No other code is changed.
cmd = "C:\R\bin\i386\Rscript.exe C:\R\test.R"
Debug.Print cmd
Shell cmd
I get
runtime error '5'
I am using the immediate window to check the paths are correct and copying them into RUN to verify that they do work.
The above outputs:
C:\R\bin\i386\Rscript.exe C:\R\test.R
It works in RUN.
The first thing I found when searching online is to add more (") as shell can handle them weirdly:
cmd = """C:\R\bin\i386\Rscript.exe""" & " " & """C:\R\test.R"""
Or any iterations of using "s in different places, output:
"C:\R\bin\i386\Rscript.exe" "C:\R\test.R"
Same error but works in RUN. I also tried them all successfully in CMD.
It seems just Shell refuses to launch R from that path. I have moved it elsewhere on my C drive with same effect.
I cannot recreate the original R installation path as that shared drive is now completely dead.
EDIT:
I changed to using ShellExecute simply to try and make Notepad ++ open, again works in cmd.
Set objShell = CreateObject("Shell.Application")
objShell.ShellExecute "C:\N\notepad++.exe", "C:\R\test_in.csv", "", "open", 1
This time I hit a "suspicious macro error" that leads me to believe that it may be an antivirus setting (macros are enabled in Access) blocking Shell from calling anything.
After days of testing I have found the solution, hopefully this can help anyone else in a similar situation. Windows Defender only blocks shell calls to non-Microsoft products, so I nested a call to PowerShell within the call to Shell:
Shell ("powershell.exe C:\R\bin\i386\Rscript.exe C:\R\test.R")
Take note you need to play around with the "s a lot ot get it working, my actual pipeline has more arguments and I had to enclose them in 5 sets of "s for it to pass through to powershell properly. IE:
Dim codePath As String: codePath = """""\\example\example"""""
Try these variations using Start or a second Command:
cmd = "Start C:\R\bin\i386\Rscript.exe C:\R\test.R"
or:
cmd = "cmd /c ""C:\R\bin\i386\Rscript.exe C:\R\test.R"""

"Access is denied" Run VB script from Excel Macro

I need to make an asynchronous job. In loop from MAIN.xlsm I want to call VB script (with different parameters) to open more Excel instances where .refreshAll method is executed. (This way I can open more files at once and don't need to wait on synchronous execution of VBA in Excel).
The last thing causing problem is permissions in Shell. To make it easier I simplified code (w/o loop & parameters). Sub OpenShell is in Excel VBA module. UAC is off, I am local admin on PC.
Sub OpenShell()
strShell = "cmd.exe /k cscript " & ThisWorkbook.Path & "\1.vbs"
Shell strShell
Exit Sub
VB script has only one line: Wscript.Echo "Running"
Result in shell: "Access is denied".

Call .reg File from Excel-VBA script

I want to call a .reg File out of my VBA script. I'm using Office/Excel 2013.
I know Excel can't run these files by itself, so i need to call the file via shell. The code i wrote doesn't work:
Sub deactivateHyperlinkWarnings()
Dim x
x = Shell("cmd /C C:\TEMP\DisableHyperlinkWarnings.reg")
End Sub
I found this piece of code somewhere on the web, but its not working. I don't even get an error message. The .reg File is located in C:\TEMP
What do i need to write to make it work?
Plus: Is it possible to suppress the MessageBoxes that are displayed when i run the .reg-File? When i start the file manually, i need to Hit "OK" like 3 Times. The people who are working with the Excelsheet later on shouldn't be seeing these things.
Instead of running cmd try to run reg. So in your case it should be x = Shell("reg import C:\TEMP\DisableHyperlinkWarnings.reg")
More info here

Running Macro from .bat with another Access db open

I need to run a few Access macros automatically periodically throughout the day, I do this by scheduling a batch file to open the relevant Access db and run the macro.
The problem that I am having is, if I am working on another Access database and therefore already have an instance of Access open, the batch file runs but only opens the database containing the macro that is supposed to run and stops. So the macro doesn't run.
Has anyone else had this issue or know how to solve it?
The batch files that task scheduler calls look like this:
start /min "C:\Program Files\Microsoft Office 15\root\office15\MSACCESS.EXE" "Q:\TC\DNI_Updater\DNIUPDATER.accdb" /X DailyUpdate
I could not find a way to get the DailyUpdate macro to run in the second Access session when using start /min to open that session.
I'm still unsure whether it's possible, but I gave up and switched to VBScript instead. With that approach, it's easy to start the second Access session minimized and run the macro ...
Option Explicit
Dim AccessExePath, DbPath, CmdLine, objShell
DbPath = "C:\Users\hans\Documents\test_hfu.accdb"
AccessExePath = "C:\Program Files (x86)\Microsoft Office\Office14\MSAccess.exe"
CmdLine = """" & AccessExePath & """ """ & DbPath & """" & " /X DailyUpdate"
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run CmdLine, 7 ' Minimize. The active window remains active.
If this approach is satisfactory, you can use the script file as your scheduled task's "Start a program" Action property ...

Pass Variable from Excel Macro to .vbs file

I have an excel button with a macro. The code simply stores the path of the workbook in a vaiable names 'MyCompletePath' and then runs a .vbs file. The code is:
MyCompletePath = ActiveWorkbook.FullName
'Run VBS file
Shell "wscript C:\Users\name\Desktop\vb.vbs", vbNormalFocus
I want to pass the variable 'MyCompletePath' from the excel file to the file which is executed using the last line.
I made some searches but didn't fully understand what their solutions do. Maybe someone can tell me how to do it.
UPDATE/EDIT: I'm now having a problem with the filepath after Shell "wscript. It has spaces in the folder name. How can I get it to work with spaces in the name?
Thank you.
You can include command line arguments after the path to your VBS file. For example:
Shell "wscript C:\Users\name\Desktop\vb.vbs BlahBlahBlah", vbNormalFocus
Then inside your VBS script, you can access them using the WScript.Arguments collection. For example:
MsgBox WScript.Arguments(0)
would pop up a message box displaying "BlahBlahBlah".
For a file path, as you indicated, which might include spaces and thus would be treated as multiple arguments to the script, I would include the argument in quotes, like this:
Shell "wscript C:\Users\name\Desktop\vb.vbs ""this has multiple words""", vbNormalFocus
based on passing argument from vba to vbs
When I write that within the vba:
Sub Macro1()
MyCompletePath = "toto"
Shell "wscript D:\\vb.vbs " & MyCompletePath
End Sub
and this in vb.vbs
MsgBox("Hello " & WScript.Arguments(0))
I do get "Hello toto"