How to execute Batch File while passing parameters from Excel

核能气质少年 提交于 2021-02-19 09:00:18

问题


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.

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

回答1:


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.

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.

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

Hope this helps.

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)

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

Save the following as test.bat

set arg1=%1
echo HELLO %1!
pause

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.

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.

Hope this helps



来源:https://stackoverflow.com/questions/41756291/how-to-execute-batch-file-while-passing-parameters-from-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!