SUMMARY: I am trying to run a .bat script on a Windows machine using Excel VBA. I have found references online describing how to do this, and I have followed the instructions contained therein. However, my .bat file is not running.
DETAILS: My .bat file ("test.bat") contains the following code:
echo off
echo This is a test...
pause
exit
It is located on my desktop, with the following path: "C:\Users\User1\Desktop". When I double-click this .bat file or call it from the command line, it exhibits the desired behavior. Namely, it pauses and waits for me to press any key.
I am trying to run this same .bat file from Excel VBA using the following code:
Sub testBatchScript()
'Print a message to the immediate window to confirm subroutine execution
Debug.Print "The subroutine is running."
'Initialize a windows shell object
Dim wsh As WshShell
Set wsh = New WshShell
'Construct the full path to the .bat file
Dim fullPath As String
fullPath = Chr(34) + "C:\Users\User1\Desktop\test.bat" + Chr(34)
'Run the .bat file
Dim eCode As Long
eCode = wsh.Run(fullPath, waitonreturn:=True, windowstyle:=1)
If eCode <> 0 Then
MsgBox ("An error occurred.")
End If
End Sub
When I run this subroutine, nothing happens. No CMD window pops up, and no message box indicating an error pops up. However, I do know that the subroutine is running, due to the message that appears in the immediate window.
I'm stumped as to why this isn't working. What's even more perplexing is that I was able to successfully call .bat scripts from VBA as recently as a few weeks ago..
Anyone have any explanation or suggestions?
UPDATE1: Following @Dhamo's suggestion in the comments below, I have updated the VBA code with error handling:
Option Explicit
Sub testBatchScript()
On Error GoTo EH:
'Print a message to the immediate window to confirm subroutine execution
Debug.Print "The subroutine is running."
'Initialize a windows shell object
Dim wsh As WshShell
Set wsh = New WshShell
'Construct the full path to the .bat file
Dim fullPath As String
fullPath = Chr(34) + "C:\Users\User1\Desktop\test.bat" + Chr(34)
'Run the .bat file
Dim eCode As Long
eCode = wsh.Run(fullPath, waitonreturn:=True, windowstyle:=1)
If eCode <> 0 Then
MsgBox ("An error occurred.")
End If
Exit Sub
EH:
MsgBox ("The error description is: " & Err.Description)
End Sub
When I run this code, still nothing happens.
UPDATE2: I ran the test code again this morning, after restarting my computer, and this time I got a pop-up message saying: "The error description is: Permission denied". I then ran the code again to see if I could replicate this error message, and there was no pop-up! Furthermore, I can't get the error message to reappear no matter how many times I run the code. So restarting seems to have done something...
The "Permission denied" message suggests that it's a security issue. Anyone have any ideas for solving it?