Execute .bat file from Excel VBA Macro

后端 未结 4 667
逝去的感伤
逝去的感伤 2020-12-18 05:14

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 kno

相关标签:
4条回答
  • 2020-12-18 05:20

    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.

    0 讨论(0)
  • 2020-12-18 05:29

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

    here, without /d cmd will open in document folder. by /d it will open in d drive, you may change this as per your easy.

    0 讨论(0)
  • 2020-12-18 05:41

    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"
    
    0 讨论(0)
  • 2020-12-18 05:43

    One way to insert a quote(") into a string is by using the character code conversion function Chr(34), 34 being the ASCII value for quotes(")

    0 讨论(0)
提交回复
热议问题