使用 VBA 在给定目录中运行批处理文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9403341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Running a batch file in a given directory using VBA
提问by Jason
When I go to my batch file's location and open it, the batch file works. My batch file is simply:
当我转到我的批处理文件的位置并打开它时,批处理文件可以工作。我的批处理文件很简单:
cd .\data
dir/b/o:n > names.txt
As you can see, I'm in my current directory and moving down to the sub directory "data" and coping all the names and creating a file called names.txt
.
如您所见,我在当前目录中并向下移动到子目录“data”并处理所有名称并创建一个名为names.txt
.
When I say
当我说
shell "location of file"
it opens the batch file, but the directory that is defaulted to is C:\my documents
, so my commands won't work because it cannot find the sub directory. I want this to be a dynamic batch file, and therefore i need to write something in VBA that will open the batch file under its current directory or something to this effect.
它打开批处理文件,但默认目录是C:\my documents
,所以我的命令将不起作用,因为它找不到子目录。我希望这是一个动态批处理文件,因此我需要在 VBA 中编写一些内容,以在其当前目录下打开批处理文件或达到此效果的内容。
How do I do this?
我该怎么做呢?
回答by Tony Dallimore
The following should give you the effect you seek.
以下应该给你你想要的效果。
My test code is:
我的测试代码是:
Option Explicit
Sub TryShell()
Dim PathCrnt As String
PathCrnt = ActiveWorkbook.Path
Call Shell(PathCrnt & "\TryShell.bat " & PathCrnt)
End Sub
My test batch file is named TryShell.bat and contains:
我的测试批处理文件名为 TryShell.bat,其中包含:
cd %1
dir *.* >TryShell.txt
I have placed my batch file in the same folder as the workbook containing my macro.
我已将批处理文件与包含我的宏的工作簿放在同一文件夹中。
The statement PathCrnt = ActiveWorkbook.Path
sets PathCrnt to the name of the directory containing the active workbook. You can set PathCrnt to whatever directory you require.
该语句PathCrnt = ActiveWorkbook.Path
将 PathCrnt 设置为包含活动工作簿的目录的名称。您可以将 PathCrnt 设置为您需要的任何目录。
When I call Shell
, I have added PathCrnt
as a parameter.
当我调用 时Shell
,我已添加PathCrnt
为参数。
In my batch file, I set the current directory to %1
which is the first parameter.
在我的批处理文件中,我将当前目录设置%1
为第一个参数。
The dir
command works as I wish because the current directory is my directory and not the system default directory.
该dir
命令按我的意愿工作,因为当前目录是我的目录而不是系统默认目录。
Hope this is clear.
希望这很清楚。
回答by assylias
C:\My Documents is probably the directory where your speadsheet is located. If you add
C:\My Documents 可能是电子表格所在的目录。如果添加
ChDir "C:\TheFolderWhereYourBatchIs"
before launching your Shell command and that should work...
在启动您的 Shell 命令之前,这应该可以工作...
Alternatively, you could change your batch file to use an absolute directory instead of a relative one.
或者,您可以更改批处理文件以使用绝对目录而不是相对目录。