Vba Shell call works with some programs but does not work with others - excel

Shell call works with some programs that I have but does not work with others. I am putting the most basic call here for opening an exe without any further commands
Shell "C:\Program Files\qBittorrent\qbittorrent.exe", 1 'works
Shell "C:\Program Files\AmiBroker\Broker.exe", 1 'works
Shell "C:\Program Files\CTrading\QuantShare\QuantShare.exe", 1 'Run-time error '5': Invalid procedure call or argument
Shell "C:\Program Files (x86)\Equis\MetaStock\MsWin.exe", 1 'same error
I am on the verge of giving up unless I meet a savior here!!
System: Windows 10 Pro Version 1909 OS Build 18363.476
Microsoft Excel 2013 64-bit

A bit of an ugly fix, but it might help:
Shell "cmd /c ""C:\Program Files\CTrading\QuantShare\QuantShare.exe""", 1
I don't have any of the programs you are having problems with, so it is a bit of a guess. If this doesn't help, the next step is cmd /c start ...

Finally, i could use ShellExecute as follows:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Target, Range("A1:A2000")) Is Nothing Then
Set objShell = CreateObject("Shell.Application")
para = "TaskManager ChangeSymbol newsymbol:" & ActiveCell.Value
objShell.ShellExecute "C:\Program Files\CTrading\QuantShare\QuantShare.exe", para, "", "open", 1
Set objShell = Nothing
Cancel = True
End If
End Sub
Can I make ShellExecute not to open a new instance of the program and rather activate the currently open instance and pass the arguments (similar to Shell call? Also how to make ShellExecute not take focus? I want the focus to stay back in Excel.

Related

Excel VBA Workbook_Open does not work when Excel is already open

I was trying to automate VBA run with its file opening from command line as below:
cmd.exe /C set MacroName=MyMacro \& EXCEL.EXE C:\\_documents\\Book2.xlsm
The VBA scripts and files are as follows:
Book2.xlsm/Module1
Sub MyMacro()
MsgBox "MyMacro is running..."
End Sub
Book2.xlsm/ThisWorkbook
Private Sub Workbook_Open()
Dim strMacroName As String
strMacroName = CreateObject("WScript.Shell").Environment("process").Item("MacroName")
If strMacroName <> "" Then Run strMacroName
End Sub
Now, the above cmd command does work, expectedly notifies me with the MsgBox, when Excel is not open. But it does not work when Excel is already being open with other project/file(s).
How can I make this work?
The problem was that when you launch an Excel file in the already open Excel instance passing environment variables through cmd.exe or command line does not work correctly for some reason, rather than as a VBA-side problem.

Trouble Deleting files programmatically in VBA

I had a hard time with Windows 7 OS to where it would think that certain folders are in usage (not allowing folder delete), when in fact they aren't.
After alot of research and trial and error, I was able to use a command that worked well on Windows 7:
rmdir /S /Q "S:\Allied MTRS\Not Scanned\FITTINGS AND FLANGES\RG AR 2686 MOVED FOR AUTO INDEXING"
When I try to run this programmatically via shell command (see code below), it gives me: "File Not Found" message.
So if you try to run it programmatically first, it won't work. Then try to run the same thing, via command line, it works fine. Of course, if you try to run it grammatically again, after that, it will give you "File Not Found" (naturally, since the folder is already deleted). If you want to retry the experiment, you have to try on another folder....
Any ideas?
Sub tryitz()
Dim s As String
Dim ReturnCode As Integer
s = "S:\Allied MTRS\Not Scanned\FITTINGS AND FLANGES\RG AR 2686 MOVED FOR AUTO INDEXING"
s = "rmdir /S /Q " + Chr(34) + Trim(s) + Chr(34)
ReturnCode = Shell(s)
End Sub
Here is a possible answer, but I am looking for something better.
But hey, if not, at least this works, just a little bit more labor in terms of writing a bit of code...
Create a batch file
DelFile.Bat, say.
The DelFile.Bat is edited by my program (programmatically).
I edit it so that it has my desired "rmdir /S /Q? statement.
Then, I run it through shell.

Using VBA to run WinSCP script

I am able to download files from SFTP in CMD window, by using following code:
WinSCP.com
# Connect to the host and login using password
open user:pw#address
# get all the files in the remote directory and download them to a specific local directory
lcd C:\Users\xx\Desktop
get *.xlsx
# Close and terminate the session
exit
I searched online and found out that I can put these codes in a bat file and use
Call Shell("cmd.exe /c C:\Users\xx\Desktop\WinSCPGet.bat", 1)
However, only the first line of the bat file WinSCP.com is being executed. It will pop up the cmd window, showing this, without doing anything else.
How to execute all the lines at one time?
Thanks
The code you have is not a Windows batch file. It's one Windows command followed by WinSCP commands. The first command runs winscp.com application, which then sits and waits for input. If you eventually close it, Windows command interpreter (cmd.exe) will carry on executing the remaining commands, failing most, as they are not Windows commands. See also WinSCP script not executing in batch file and WinSCP FAQ Why are some WinSCP scripting commands specified in a batch file not executed/failing?
So you either have to save the commands (open to exit) to a WinSCP script file (say script.txt) and execute the script using the /script switch:
Call Shell("C:\path\winscp.com /ini=nul /script=c:\path\script.txt")
Alternatively, specify all commands on WinSCP command line, using the /command switch:
Call Shell("C:\path\winscp.com /ini=nul /command ""open user:pw#address"" ""lcd C:\Users\xx\Desktop"" ""get *.xlsx"" ""exit""")
Regarding the quotes: With the /command switch, you have to enclose each command to double-quotes. In VBA string, to use a double-quote, you have to escape it by doubling it.
Also note that you generally should use the /ini=nul switch to isolate the WinSCP script run from your WinSCP configuration. This way you can also make sure that the script will run on other machines. Your script won't, as it lacks the -hostkey switch to verify the SSH host key fingerprint. Using the /ini=nul will help you realize that.
You can have WinSCP GUI generate complete command-line (including the -hostkey) for you.
See also Automating file transfers to SFTP server with WinSCP.
I like this small and compact procedure, and use it in my own projects. No temp-files required. Fast and reliable.
Parse a string src (an absolute filepath) to uploadImageByFTP. Etc. C:\Users\user\Desktop\image.jpg, and the file will be uploaded.
Replace:
<username> with FTP-User
<password> with FTP-Password
<hostname> with FTP-hostname (etc. example.com)
<WinSCP.com path> with path on your WinSCP-client (etc. C:\Program Files (x86)\WinSCP\WinSCP.com. Caution: WinSCP.com and not WinSCP.exe)
<FTP-path> with path on your FTP-client (etc. /httpdocs/wp-content/uploads)
Sub uploadImageByFTP(src As String)
Dim script As Object: Set script = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
'Not empty
If (src <> vbNullString) Then
'Execute script
script.Run _
"""<WinSCP.com path>"" " + _
"/ini=nul " + _
"/command " + _
"""open ftp://<username>:<password>#<hostname>/"" " + _
"""cd <FTP-path>"" " + _
"""put " & """""" & src & """""" & """ " + _
"""close"" " + _
"""exit""", windowStyle, waitOnReturn
End If
End Sub
WScript.Shell is more powerful than the default Shell(), as you can append a waitOnReturn-command; this tells VBA, that further execution isn't allowed before the file(s) have been uploaded to the FTP-server.
Change windowStyle to 0, if you don't like the command prompt to open on each execution.

Shell command on Excel with long path name don't work

I have a batch file run.bat in a network folder "L:\Common Data\myfile" and i want to execute it from an Excel's macro.
Googling around I found these sintax:
Call Shell(Environ$("COMSPEC") & " /k L:\Common Data\myfile\run.bat", vbNormalFocus)
but it fails because it reads only "L:\Common".
I tryed many suggestion found on Internet but no one succeeded.
Someone have a solution?
Path names with spaces have to be wrapped in quotes.
Call Shell(Environ$("COMSPEC") & " /k ""L:\Common Data\myfile\run.bat""", vbNormalFocus)

Excel Macro to Open EXE

I am trying to create a macro that will open the file "test.exe" on drive F/. I get "runtime error 5" when running this code below.
Sub MacroTangoMike()
' MacroTangoMike Macro
RetVal = Shell("F:/test.exe", 1)
End Sub
It works fine though if test.exe is on the C/ drive.
Error 5 is access denied. Are you sure you have the execute permission on the EXE on the F: drive?
Also you should probably be using backslashes \ in your paths on Windows rather than /.

Resources