使用 VBA 在给定目录中运行批处理文件
当我转到批处理文件的位置并打开它时,批处理文件就可以工作。我的批处理文件很简单:
cd .\data
dir/b/o:n > names.txt
如您所见,我在当前目录中移动到子目录“data”并复制所有名称并创建一个名为 names.txt
的文件。
当我说它
shell "location of file"
打开批处理文件时,但默认的目录是C:\my Documents
,所以我的命令将不起作用,因为它找不到子目录。我希望这是一个动态批处理文件,因此我需要在 VBA 中编写一些内容来打开其当前目录下的批处理文件或达到此效果的内容。
我该怎么做?
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
.
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.
How do I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下内容应该会给您带来您想要的效果。
我的测试代码是:
我的测试批处理文件名为 TryShell.bat 并包含:
我已将批处理文件放置在与包含宏的工作簿相同的文件夹中。
语句
PathCrnt = ActiveWorkbook.Path
将 PathCrnt 设置为包含活动工作簿的目录名称。您可以将 PathCrnt 设置为您需要的任何目录。当我调用
Shell
时,我添加了PathCrnt
作为参数。在我的批处理文件中,我将当前目录设置为
%1
,这是第一个参数。dir
命令按照我的意愿工作,因为当前目录是我的目录,而不是系统默认目录。希望这一点是清楚的。
The following should give you the effect you seek.
My test code is:
My test batch file is named TryShell.bat and contains:
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.When I call
Shell
, I have addedPathCrnt
as a parameter.In my batch file, I set the current directory to
%1
which is the first parameter.The
dir
command works as I wish because the current directory is my directory and not the system default directory.Hope this is clear.
C:\My Documents 可能是电子表格所在的目录。如果您在启动 Shell 命令之前添加
,那么应该可以工作...
或者,您可以更改批处理文件以使用绝对目录而不是相对目录。
C:\My Documents is probably the directory where your speadsheet is located. If you add
before launching your Shell command and that should work...
Alternatively, you could change your batch file to use an absolute directory instead of a relative one.