Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute .bat file from Excel VBA Macro

Im having a problem with my excel vba macro. I need it to execute a batch file which is in the same folder as the excel workbook. The code works well sometimes. I don't know whats causing the error. Here's the code:

Sub writebatch()
  Sheets("code").Select
  Application.DisplayAlerts = False
  ActiveWorkbook.SaveAs FileName:=ThisWorkbook.path & "\code.bat",
  FileFormat:=xlTextPrinter, CreateBackup:=False
  Application.DisplayAlerts = True
  ThisWorkbook.Saved = True
  Shell "cmd.exe /k cd " & ThisWorkbook.path & "&&code.bat"
  Application.Quit
End Sub

It writes the batch file, but then doesn't execute it. Only once I got the command window to not close and it said the code.bat file could not be found. So the changedir command worked. Is it possible to run cmd.exe and run the code.bat with the relative path without having to changedir?

like image 576
Matteo Cuellar Vega Avatar asked Nov 23 '12 13:11

Matteo Cuellar Vega


2 Answers

First of all, when you launch a CMD instance you need to enclose the entire CMD argument if you use any type of operators (&):

CMD /K "command1 & command2"

And then enclose the sub-internal arguments, like this:

CMD /K "command "path with spaces" & command"

So you need to do something like this:

Shell "cmd.exe /k ""cd " & """ & ThisWorkbook.path & """ & " && code.bat"""

Notice I've used """ to escape a quote, but I don't know the way to escape a quote in VBA.

PS: remember to also enclose the code.bat if you have spaces, but ONLY if you have spaces.

like image 155
ElektroStudios Avatar answered Oct 14 '22 12:10

ElektroStudios


I'm pretty sure the problem is down to this line

Shell "cmd.exe /k cd " & ThisWorkbook.path & "&&code.bat"

You need a space in front of the && to separate it from the cd command and after it to separate it from the code.bat.

Shell "cmd.exe /k cd " & ThisWorkbook.path & " && code.bat"
like image 26
Bali C Avatar answered Oct 14 '22 11:10

Bali C