File not found error when running an exe using Shell function - vba

I am running a sub from a userform that is supposed to run an exe file, found in the working folder, as follows:
Sub RunProcessor()
If MsgBox("Run simulation?", vbYesNo) = vbNo Then
Exit Sub
Else
ChDir ThisWorkbook.Path
Shell ("runsims.exe")
End If
End Sub
This was working fine on my local drive, but started to fail when I moved everything to a server drive (Run-time error 5 on the Shell function call line).
I know in cmd, when you are working on the C: drive and do a cd L:\...\...\ call, you then need to enter L: as well, so I tried to insert this line of code above the other Shell call: Shell (Left(ThisWorkbook.Path, 2)) but this also failed. How can I have "runsims.exe" run, given that it is always in the current working drive?

ChDir will only work to change the current directory to another on the same drive - you need to use ChDrive first if you want to switch to a folder on a different drive.
Better yet, pass the full path to Shell and skip changing the current directory.
Sub RunProcessor()
If MsgBox("Run simulation?", vbYesNo) = vbYes Then
Shell (ThisWorkbook.Path & "\runsims.exe")
End If
End Sub

Related

MS Access throwing error 2001 when running VBA script to make a directory in a Macro or as sub script

I have the following VBA script in MS Access to check for a directory and make it if it does not exist:
Public Function MakeReportDirct()
Dim fDate As String
Dim sFolderPath As String
Dim oFSO As Object
fDate = Format(Now(), "YYYY-MM")
sFolderPath = "\\satco-file01\COMPANYSHAREDFOLDERS\Reporting\Nuvo\Daily Reports\" & fDate
Set oFSO = CreateObject("Scripting.FileSystemObject")
If oFSO.FolderExists(sFolderPath) Then
End
End If
MkDir sFolderPath
End Function
When I run the code alone in the VBA window, it works perfectly. However, when I try to run the code from a Macro or when I try to call from another VBA script:
Public Function ChartwellVendor()
Call MakeReportDirct
Call ChartwellVendorExport
Call ChartwellVendorEmail
End Function
It gives the "Macro Single Step" error:2001
I have enabled every location I can think of (the database location, the export location, the location the directory will be created) as a "Trusted Location".
Any help would be greatly appreciated!
The End statement "Terminates execution immediately".
When you run MakeReportDirct alone, that accomplishes what you want: MkDir is not executed when the folder already exists.
But when you run it from within ChartwellVendor, you want other procedures to run after MakeReportDirct. However, the End statement terminates all further processing, so those other procedures don't run.
You could avoid that problem by replacing End with Exit Function. Then MakeReportDirct could terminate but still allow processing to continue with the next line in ChartwellVendor
Another approach would be to flip the logic of your If block condition. If the folder does not exist, run MkDir inside that code block.
If Not oFSO.FolderExists(sFolderPath) Then
MkDir sFolderPath
End If

VBA - Execute or Run .bat File Inside Macro

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

excel vba won't execute .bat but manually executing bat works fine

Hi I have a perfectly working bat named: start.bat
containing:
start C:\Users\*user*\Documents\*path*\hidebat.vbs
and once it is manually opened it works perfectly, meaning it opens hidebat.vbs, which opens a .bat minimized which uploads files to my cloud. Hence it's verified.
I've added
pause
to the start.bat to see what it does and when I tell excel to open the start.bat it will open cmd and display the exact command as required, but it will not execute the hidebat.vbs.
I expect that there is somehow some path constraint or environment constraint when it is run from excel that prevents it to actually reach out of that limited environment.
Within excel I have tried calling the .bat in 3 different ways with:
Dim path As String
path = Application.ActiveWorkbook.path
path = path & "\"
Dim MY_FILENAME3 As String
MY_FILENAME3 = path & "start.bat"
1.
retVal = Shell(MY_FILENAME3, vbNormalFocus)
' NOTE THE BATCH FILE WILL RUN, BUT THE CODE WILL CONTINUE TO RUN.
If retVal = 0 Then
MsgBox "An Error Occured"
Close #FileNumber
End
End If
2.
PathCrnt = ActiveWorkbook.path
Call Shell(PathCrnt & "start.bat")
3.
Dim batPath As String: batPath = path
Call Shell(Environ$("COMSPEC") & " /c " & batPath & "start.bat", vbNormalFocus)
Does anybody have any clue on why it will not execute the .bat file, or what I could do to ensure it will run correctly?
Note. I think it is because it opens the default path, so I'm gonna tell it to "cd" to the actual path where the excel is saved and where the .bat files are.
Yes that was it, the path was set to some random/standard/working/current path by command, so I had to add:
Print #FileNumber, "cd " & path
to the excel macro
so that start.bat looked like:
cd *path*
start *path*\hidebat.vbs
Hope this helps future me's.

Shell command will not run exe file [duplicate]

I am running a sub from a userform that is supposed to run an exe file, found in the working folder, as follows:
Sub RunProcessor()
If MsgBox("Run simulation?", vbYesNo) = vbNo Then
Exit Sub
Else
ChDir ThisWorkbook.Path
Shell ("runsims.exe")
End If
End Sub
This was working fine on my local drive, but started to fail when I moved everything to a server drive (Run-time error 5 on the Shell function call line).
I know in cmd, when you are working on the C: drive and do a cd L:\...\...\ call, you then need to enter L: as well, so I tried to insert this line of code above the other Shell call: Shell (Left(ThisWorkbook.Path, 2)) but this also failed. How can I have "runsims.exe" run, given that it is always in the current working drive?
ChDir will only work to change the current directory to another on the same drive - you need to use ChDrive first if you want to switch to a folder on a different drive.
Better yet, pass the full path to Shell and skip changing the current directory.
Sub RunProcessor()
If MsgBox("Run simulation?", vbYesNo) = vbYes Then
Shell (ThisWorkbook.Path & "\runsims.exe")
End If
End Sub

Changing working directory from Excel vba shell

For work, I'm trying to run a Python script from an Excel VBA macro.
The macro is as follows -
Sub Plot()
Shell "C:\Users\maheshda\AppData\Local\Continuum\Anaconda3\python.exe C:\Users\maheshda\Tool\Tool\Main.py", vbNormalFocus
End Sub
The script runs just fine when run from the command line, but unfortunately, because I'm using relative filepaths in the Python script (at one point, I call files from '../Input/') the script crashes because the current working directory isn't C:\Users\maheshda\Tool\Tool.
How can I change the working directory from within the macro? Thank you!
This is a trivial task in VBA, use ChDir:
ChDir Statement
Changes the current directory or folder.
Syntax
ChDir path
The required path argument is a string expression that identifies which directory or folder becomes the new default directory or folder. The path may include the drive. If no drive is specified, ChDir changes the default directory or folder on the current drive.
Since your main.py resides in C:\Users\maheshda\Tool\Tool\, use the following right before calling the Python script:
ChDir "C:\Users\maheshda\Tool\Tool"
Or (since it is on drive C):
ChDir "\Users\maheshda\Tool\Tool"
Extending on Wiktor Stribiżew's answer and comments, the sub below can be used to change the Current Directory in any case.
Public Sub Change_Current_Directory(NewDirectoryPath as string)
Dim CurrentDirectoryPath as string
CurrentDirectoryPath = curdir
if Strings.StrComp(Strings.Left(CurrentDirectoryPath,2), Strings.Left(NewDirectoryPath,2), vbTextCompare) then
ChDrive Strings.Left(NewDirectoryPath,1)
end if
ChDir NewDirectoryPath
End Function
Happy coding!
FCastro, why did you bother with that StrComp line? And, for that matter, why bother with the Strings object?
I suppose if the drive were external and hadn't been accessed yet it might take a moment, but as long as the path is not expected to be a USB/CD/DVD/etc..., then:
Public Sub Change_Current_Directory(NewDirectoryPath as string)
ChDrive Left(NewDirectoryPath,1)
ChDir NewDirectoryPath
End Function
If your behavior is to open an excel window and then open your recent file, please note that you should not forget to add change Drive and then change Directory into your VBA code.
Cause the Excel always start with the default Directory even it's just open your recent file !
Dim ThisWorkbookPath As String
Dim ThisWorkbookPathParts As Variant
ThisWorkbookPath = ThisWorkbook.Path
ThisWorkbookPathParts = Split(ThisWorkbookPath, _
Application.PathSeparator)
ChDrive ThisWorkbookPathParts(LBound(ThisWorkbookPathParts))
ChDir ThisWorkbookPath