简体   繁体   English

使用Excel VBA运行CMD命令

[英]Using Excel VBA to run a CMD command

I would like to use Excel VBA to run a CMD command. 我想使用Excel VBA运行CMD命令。

The basic cmd command is: 基本的cmd命令是:

"C:\Program Files\example program.exe" -w C:\Program files\outputfile.file "dir1" "dir2" "dir n+1"

The first part is the location of the program that will merge the files together. 第一部分是将文件合并在一起的程序的位置。 The second part is the file location of the outputted merged files. 第二部分是输出的合并文件的文件位置。 And the "dir1".... is the files that will be merged together. 而“ dir1” ....是将合并在一起的文件。

I have code that lists the files to be merged but struggling to get the CMD code to get it so it does what I want as mentioned above. 我有列出要合并的文件的代码,但是却很难获得CMD代码来获取它,因此它如上所述做了我想要的。 I have tried the following: 我尝试了以下方法:

   Sub RunCMD()

        Dim wsh As Object
        Set wsh = VBA.CreateObject("WScript.Shell")
        Dim waitOnReturn As Boolean: waitOnReturn = True
        Dim windowStyle As Integer: windowStyle = 1
        Dim locationofprogram as string
       'dir of program that will do the merge
        Dim outputfolder as string
       'dir of where the merged file will go
        Dim listoffiles as string
       'list of files to be merged

        wsh.Run "cmd.exe /S /C locationofprogram & " " & "-w" & " " & outputfolder & " " & listoffiles, windowStyle, waitOnReturn

    End Sub

Thanks for the help! 谢谢您的帮助!

If in doubt, send the text to the Immediate Window to see if it still matches the syntax using: 如有疑问,请使用以下命令将文本发送到“即时窗口”以查看其是否仍与语法匹配:

 Debug.Print "cmd.exe /S /C " & locationofprogram & " " & "-w" & " " & outputfolder & " " & listoffiles

If that works, use: 如果可行,请使用:

 wsh.Run "cmd.exe /S /C " & locationofprogram & " " & "-w" & " " & outputfolder & " " & listoffiles, windowStyle, waitOnReturn

You can always create a .bat file, run the file, then delete it. 您始终可以创建.bat文件,运行该文件,然后将其删除。

MyFile = "C:\Bat-File\Bat-File.bat"

fnum = FreeFile()
Open MyFile For Output As #fnum
Print #fnum, "C:\Program Files\example program.exe -w C:\Program files\outputfile.file dir1 dir2 dir n+1"    
Close #fnum

Shell MyFile, vbNormalFocus

' wait 10 seconds to let bat file finnish
newHour = Hour(Now()) 
newMinute = Minute(Now()) 
newSecond = Second(Now()) + 10 
waitTime = TimeSerial(newHour, newMinute, newSecond) 
Application.Wait waitTime

' delete bat-file
kill MyFile

I can't test that example program runs without the " around the dir´s so you have to see what happens. 我无法测试示例程序是否在目录周围没有“”,因此您必须查看会发生什么。
But if it does not work you need to double enclose the " or use & CHR(34) & 但是,如果它不起作用,则需要将“”括起来或使用& CHR(34) &

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM