VBA SHELL COMMAND not executing - excel

I am novice to VBA shell. So i request an explanation to understand how things work.
Through EXCEL VBA, I would like to create a *.bat file and execute the same automatically. However my command lines ONLY creates the file and does not execute it. Please suggest.
Sub Create_Motor_Model()
Application.ScreenUpdating = False
CURRENT_SHEET = "Script"
Output_path = ActiveWorkbook.Path
InputData1 = Cells(1, 2)
file_output = Output_path & "\" & "Input.bat"
Open file_output For Output As #1
Print #1, Chr(34) & InputData1 & Chr(34) & " -b -i " & CURRENT_SHEET & ".mac -o Output.out"
Close #1
Shell ActiveWorkbook.Path & "\Input.bat"
End Sub

Related

How to make this hard-coded file path dynamic?

The code should pass "File Path" in to the File Picker dialog window and upload/attach the file. I'm consistently getting an error.
VBA Code (error at Shell and asking for Object):
Sub AttachFile()
ufile = "D:\Desktop\Movement Pass.txt"
vbsFile = "D:\Downloads\Selenium Basic\Attachment.vbs"
Shell "WScript.exe " & vbsFile & " " & ufile
End Sub
VB Script - Attachment.vbs (error at Arguments):
Set WshShell = CreateObject("WScript.Shell")
Application.wait Now + TimeSerial(0, 0, 5)
Ret = WshShell.AppActivate("Open")
WshShell.Run "cmd.exe /c echo " & Wscript.Arguments(0) & "| clip", 0, True
WshShell.SendKeys "^{v}"
With AutoIt it worked for hard-coded file paths. I want the file path dynamically (so that I can run a loop from Excel VBA). Shell command does not compile and AutoIt does not allow dynamic paths in VBA.
I am looking for a solution in VBA and Shell command. AutoIt dynamic file path in VBA can be a solution too. I know this is not the right method but this is what I know:
VBA.Shell "Explorer D:\Seleninum\VB\Get_File_Name.exe", vbNormalFocus
Paths passed as command line argument need to be quoted if they may contain spaces:
Sub AttachFile()
ufile = "D:\Desktop\Movement Pass.txt"
vbsFile = "D:\Downloads\Selenium Basic\Attachment.vbs"
Shell "WScript.exe """ & vbsFile & """ """ & ufile & """"
End Sub

Record in a .txt file the generated results of an .exe

I have and Excel file which contains the data for a Python code. Python code is called from a .exe, and I can see in the PowerShell the results which that code is generating.
Sub Button()
Dim strPName As String
Dim strData As String
strPName = Range("H24").Text
strData = "--inputs"
Call Shell("""" & strPName & """ """ & strData & """", vbNormalFocus)
End Sub
When I have issues in the code or with the data input, the PowerShell is switch off and I cannot review which was the issue.
I want to include in the button code an automatic .txt file generation, which records the PowerShell text and let me review it after the stop.
I found here How to save the ouput of shell command into a text file in VBA the following command:
Shell "ftp -n -i -g -s:" & vPath & "abc.txt " & vFTPServ & " >> test.txt", vbNormalFocus
But I don't know how to connect it properly in my current button.
Could you give me some suggestions of how could I solve it?

Call .com file with parameters using VBA WScript.Shell

I'm using Excel to upload some files onto an server with WinSCP.
This example works:
Sub FTP_upload()
Dim logfile, ftp_login, file_to_upload, upload_to_folder As String
logfile = "D:\temp\ftp.log"
ftp_login = "ftp://ftp_mydomain:mypassword#mydomain.com/"
file_to_upload = "D:\tmep\myfile.txt"
upload_to_folder = "/myfolder/"
'upload the file
Call Shell("C:\Program Files (x86)\WinSCP\WinSCP.com /log=" & logfile & " /command " & """open """ & ftp_login & " " & """put " & file_to_upload & " " & upload_to_folder & """ " & """exit""")
End Sub
I now want Excel to wait until the shell has closed.
Using the information from Wait for shell command to complete, I put it together this code:
Sub FTP_upload_with_wait()
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim errorCode As Integer
Dim logfile, ftp_login, file_to_upload, upload_to_folder As String
logfile = "D:\temp\ftp.log"
ftp_login = "ftp://ftp_mydomain:mypassword#mydomain.com/"
file_to_upload = "D:\tmep\myfile.txt"
upload_to_folder = "/myfolder/"
execute_string = "C:\Program Files (x86)\WinSCP\WinSCP.com /log=" & logfile & " /command " & """open """ & ftp_login & " " & """put " & file_to_upload & " " & upload_to_folder & """ " & """exit"""
errorCode = wsh.Run(execute_string, windowStyle, waitOnReturn)
End Sub
Unfortunately, this doesn't work. Excel reports:
run-time error '-2147024894 (80070002)'
Automation error
The system cannot find the file specified
When I replace the string this way, it works:
execute_string = "notepad.exe"
It seems that wsh.Run doesn't like the quotation marks.
How can I make this work?
The path to WinSCP contains spaces, so you need to wrap it to double-quotes (which need to be doubled to escape them in VBA string):
execute_string = """C:\Program Files (x86)\WinSCP\WinSCP.com"" ..."
But that's only the first set of quotes that is wrong in your command.
The correct command would be like:
execute_string = """C:\Program Files (x86)\WinSCP\WinSCP.com"" " & _
"/log=" & logfile & " /command " & _
"""open " & ftp_login & """ " & _
"""put " & file_to_upload & " " & upload_to_folder & """ " & _
"""exit"""
Assuming that none of logfile, ftp_login, file_to_upload and upload_to_folder contains spaces, in which case would would need a way more double-quotes.
Read ore about WinSCP command-line syntax
The Call Shell must have some heuristics that adds the quotes around C:\Program Files (x86)\WinSCP\WinSCP.com. Though it's just a pure luck that the rest of the command-line works, the quotes are wrong there too. So even your first code is wrong. It runs the following command:
"C:\Program Files (x86)\WinSCP\WinSCP.com" /log=D:\temp\ftp.log /command "open "ftp://ftp_mydomain:mypassword#mydomain.com/ "put D:\tmep\myfile.txt /myfolder/" "exit"
(Note the misplaced quotes around open)

Merging two text files using Shell script in VBA

I have three String varibales in my VBA code as below:
Dim FilePath As String
Dim FooterFilePath As String
Dim PlusChar As String
FilePath = Application.ActiveWorkbook.Path & "\Bin\file.txt"
FooterFilePath = Application.ActiveWorkbook.Path & "\Bin\footer.txt"
PlusChar = Chr(43) 'i.e. "+" sign
Now I am trying to merge FilePath and FooterFilePath and write the combined result in FilePath again i.e. overwriting it. For that I am using followng line which doesn't work:
Shell "cmd.exe copy /c & FilePath & PlusChar & FooterFilePath & FilePath", 0
I know I have syntaxing issue here but I just don't know how to pass three variables into Shell command.
You have to put the variables outside the enclosing double-quotes. also you should insert blanks between the different names so that your command does not get the names combined in one name. Try this:
Shell "cmd.exe copy /c " & FilePath & " " & PlusChar & " " & FooterFilePath & " " & FilePath, 0
But:
There's no reason to have a variable for the +
Your drive's name is missing in the paths
/C is an option for the cmd program, not for the copy command.
It is useful to print that expression in the immediate window to verify it before execution. To do so, you can put it in a String variable and debug.print it before execution:
This would be correct:
Dim FilePath As String, FooterFilePath As String, myCommand As String
FilePath = Application.ActiveWorkbook.Path & "C:\Bin\file.txt"
FooterFilePath = Application.ActiveWorkbook.Path & "C:\Bin\footer.txt"
myCommand = "cmd /c copy " & FilePath & " + " & FooterFilePath & " " & FilePath
Debug.Print myCommand
Shell myCommand, 0

Calling BAT with VBA - CMD Loads and Closes Immediately

I'm using VBA to write a command file and a BAT file which calls PLink to log in to a server and run a script. The Plink portion is now functioning as expected thanks to some help on here. Unfortunately VBA seems to be having some difficulty with opening the cmd and finding plink as a usable command.
I've tried multiple different ways of calling it, but the results are all the same. The cmd prompt opens and then closes immediately giving me an error stating:
"plink is not recognized as an internal or external command, operable program, or batch file."
The files generate perfectly, and if I run the bat file outside of VBA, it runs as expected. With the files, I keep a copy of plink.exe on the desktop. I've even tried adding a copy of cmd.exe to the desktop with the links and plink.exe as well, but I get the same problem.
Here are some of the ways I've tried, though modified for my code: 1 2 3
Here's the most recent code for the macro:
Dim vPath As String
Dim vscript As String
UserID = Range("F1").Value
Passwd = Range("F2").Value
Server = Range("F3").Value
StartDate = Range("F4").Value
EndDate = Range("F5").Value
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CopyFile "C:\Program Files (x86)\PuTTY\plink.exe", "C:\Users\MikeDesktop\"
'fso.CopyFile "C:\Windows\System32\cmd.exe", "C:\Users\Mike\Desktop\"
vPath = "C:\Users\Mike\Desktop"
Open vPath & "\pcmd.txt " For Output As #1
Print #1, "cd /opt/test/srt"
Print #1, "./srt.tool " & StartDate & " " & EndDate & " > /opt/test/srt/test.txt &"
Print #1, "rm test.txt"
Print #1, "sleep 60; exit"
Close #1
Open vPath & "\Chg.bat" For Output As #1
Print #1, "plink " & UserID & "#" & Server & " -pw " & Passwd & " < " & vPath & "\pcmd.txt"
Close #1
vscript = vPath & "\Chg.bat"
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 5
wsh.Run vscript, windowStyle, waitOnReturn
Application.Wait (Now + TimeValue("0:01:00"))
Kill vPath & "\Chg.bat"
Kill vPath & "\pcmd.txt"
Kill vPath & "\plink.exe"
If someone can tell me why the cmd isn't recognizing plink as an option, that would be much appreciated
Either pass the path to plink.exe in the batch file, or make sure that %Path% includes the folder that contains plink.exe.

Resources