在使用VBA给定的目录中运行一个批处理文件 [英] Running a batch file in a given directory using VBA

查看:219
本文介绍了在使用VBA给定的目录中运行一个批处理文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我去我的批处理文件的位置并打开它,批处理文件的工作。我的批处理文件很简单:

  CD \\数据
DIR / B / O:N> names.txt中

正如你所看到的,我在我的当前目录中,向下移动到子目录数据和应对所有的名字,并创建一个名为 names.txt中

当我说

 壳文件位置

它打开批处理文件,但是这是默认的目录为 C:\\我的文档,所以我的命令不会工作,因为它无法找到子目录。我希望这是一个动态的批处理文件,因此我需要编写VBA中的东西,这将打开它的当前目录或东西此作用下,该批处理文件。

我如何做到这一点?


解决方案

下面应该给你你所寻求的效果。

我的测试code是:

 显式的选项
子TryShell()  昏暗PathCrnt作为字符串  PathCrnt = ActiveWorkbook.Path
  呼叫壳牌(PathCrnt&安培;\\ TryShell.bat&放大器; PathCrnt)结束小组

我测试的批处理文件被命名为TryShell.bat并包含:

  CD 1%
。DIR *> TryShell.txt

我已经把我的批处理文件相同的文件夹为包含我的宏工作簿。

语句 PathCrnt = ActiveWorkbook.Path 设置PathCrnt含有活性工作簿中的目录的名称。您可以设置为PathCrnt您需要任何目录。

当我称之为壳牌,我已经加入 PathCrnt 作为参数。<​​/ P>

在我的批处理文件,我将当前目录%1 这是第一个参数。

DIR 命令的工作,我想是因为当前目录是我的目录,而不是系统默认的目录。

希望这是显而易见的。

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?

解决方案

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:

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.

When I call Shell, I have added PathCrnt 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.

这篇关于在使用VBA给定的目录中运行一个批处理文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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