从Excel传递参数时如何执行批处理文件 [英] How to execute Batch File while passing parameters from Excel

查看:77
本文介绍了从Excel传递参数时如何执行批处理文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试运行放置在特定路径下的批处理文件.该文件需要用户输入,我希望从Excel单元格为其传递参数.Excel中批处理文件的这种执行应通过使用单击命令按钮来进行.

I am trying run a batch file placed at a particular path. The file requires user inputs for which I want the parameters to be passed from Excel cells. This execution of the batch file within Excel should happen by usage of click command button.

我是VBA的新手.我尝试了以下代码,但是在单击按钮时没有任何反应.

I am new to VBA. I tried the following code, but on clicking the button nothing is happening.

Private Sub CommandButton2_Click()

   sid = Excel.Worksheets("Sheet1").Range("I8").Value
   user = Excel.Worksheets("Sheet1").Range("I9").Value
   Password = Excel.Worksheets("Sheet1").Range("I10").Value
   msg = "hi"
   Shell ("CMD.EXE /c C:\Users\shashank.b03\Desktop\test_CMD.bat" & sid &" "& user &" "& password &" ")

End Sub

推荐答案

以下是我测试过的示例,应该可以满足您的要求.它只是调用shell命令,并将其传递给命令字符串.

Here is an example which I have tested and should work fine for you. It just calls the shell command and passes it a command string.

您可以在字符串&中更改批处理文件所在的路径.如果您不想在运行时显示Shell窗口,请使用vbHide而不是vbNormalFocus.

You can change the path where your batch file is in the string & if you don't want to show the shell window when you're running this use vbHide instead of vbNormalFocus.

您只需要稍微更改一下,即可将单元格值放入sid,user和password变量中.

You'll just have to change this a bit to put the cell values into the sid, user and password variables.

希望这会有所帮助.

Dim sid As String
Dim user As String
Dim password As String

CommandString = "c:\test.bat" + " " + sid + " " + user + " " + password
Call Shell("cmd.exe /c" & CommandString, vbNormalFocus)

这是从shell使用参数和批处理文件的更基本示例.

Here is a more basic example of using parameters and a batch file from shell.

将以下内容另存为test.bat

Save the following as test.bat

set arg1=%1
echo HELLO %1!
pause

将此代码放在excel的按钮或其他组件中;

Put this code inside a button or some other component in excel;

Private Sub CommandButton1_Click()
Dim sid As String
sid = "Shashank"
CommandString = "c:\test.bat" + " " + sid
Call Shell("cmd.exe /c" & CommandString, vbNormalFocus)
End Sub

确保保存批处理文件的路径与命令字符串中的路径相同.

Make sure that the path where the batch file is saved is the same as the one in commandstring.

运行此命令时,您将看到变量sid中保存的字符串被传递到批处理文件并被使用.您应该可以从这里开始工作.

When this is run, you'll see the string held in the variable sid is passed to the batch file and used. You should be able to get it working from here.

希望这会有所帮助

这篇关于从Excel传递参数时如何执行批处理文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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