从Excel VBA宏执行.bat文件 [英] Execute .bat file from Excel VBA Macro

查看:5836
本文介绍了从Excel VBA宏执行.bat文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

林有我的excel VBA宏的一个问题。我需要它来执行批处理文件是在同一文件夹中的Excel工作簿。在code效果很好的时候。我不知道什么导致错误。这里的code:

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

它写批处理文件,但不执行它。只有一次我得到了命令窗口不关闭,故称code.BAT文件无法找到。所以changedir命令工作。是否有可能运行CMD.EXE并运行code.BAT与相对路径,而无需changedir?

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?

推荐答案

首先,当你启动CMD例如,你需要的,如果你使用任何类型的运营商来包围整个CMD参数(安培):

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"""

注意我用,逃跑报价,但我不知道逃避VBA报价的方式。

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

PS:记得附上也是在 code.BAT 如果您有空间,但前提是你有空格

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

这篇关于从Excel VBA宏执行.bat文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆