Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
988 views
in Technique[技术] by (71.8m points)

windows - Running a batch file in a given directory using 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...