How do you run a .exe with parameters using vba's shell()? - excel

I have a target file path that is structured like example below.
C:\Program Files\Test\foobar.exe /G
What I need to do is be able to execute this file using VBA's shell() command.
How do I have to format the file path to tell Shell() that there is an argument that it needs to call along with running the .exe
What I've read/tried (with no avail) is below with the results to the right.
file = """C:\Program Files\Test\foobar.exe"" /G" <---Bad file name or number (Error 52)
shell(file)
file2 = "C:\Program Files\Test\foobar.exe /G" <---file never found
shell(file2)
I've succeeded with running other .exe's using shell() so I know it's not a problem with VBA or the function.
Example:
works = "C:\Program Files\Test\test.exe"
shell(works)
I'm not particularly familiar with the process involved with executing files that require additional parameters so if I misspeak or you need more information, please let me know.

This works for me (Excel 2013):
Public Sub StartExeWithArgument()
Dim strProgramName As String
Dim strArgument As String
strProgramName = "C:\Program Files\Test\foobar.exe"
strArgument = "/G"
Call Shell("""" & strProgramName & """ """ & strArgument & """", vbNormalFocus)
End Sub
With inspiration from here https://stackoverflow.com/a/3448682.

Here are some examples of how to use Shell in VBA.
Open stackoverflow in Chrome.
Call Shell("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" & _
" -url" & " " & "www.stackoverflow.com",vbMaximizedFocus)
Open some text file.
Call Shell ("notepad C:\Users\user\Desktop\temp\TEST.txt")
Open some application.
Call Shell("C:\Temp\TestApplication.exe",vbNormalFocus)
Hope this helps!

The below code will help you to auto open the .exe file from excel...
Sub Auto_Open()
Dim x As Variant
Dim Path As String
' Set the Path variable equal to the path of your program's installation
Path = "C:\Program Files\GameTop.com\Alien Shooter\game.exe"
x = Shell(Path, vbNormalFocus)
End Sub

sTempBAT = "d:\tempLog.txt"
Set shellwindows = GetObject("new:9ba05972-f6a8-11cf-a442-00a0c90a8f39")
Set itemobj = shellwindows.Item()
itemobj.document.Application.ShellExecute sTempBAT, "", "", "open", 0
An alternative way to call shell function
https://blog.sevagas.com/IMG/pdf/bypass_windows_defender_attack_surface_reduction.pdf

Related

How to use Call Shell when there are commas in a folder directory?

I am trying to use Call Shell to open up windows explorer to a pre-determined directory saved as string.
e.g. FolderDirectory = P:/Address, Postcode
Then
Call Shell("explorer.exe" & " " * FolderDirectory, vbNormalFocus)
It works when there is no comma in the directory but when there is a comma it just opens up the documents directory.
Any ideas?
I made a folder named Address, Postcode in my Temp Folder and this code worked for me:
Dim FolderDirectory As String
FolderDirectory = "C:\Temp\Address, Postcode"
Call Shell("explorer.exe " & """" & FolderDirectory & """", vbNormalFocus)
Hope you can adapt it to your needs
It looks like when there is a comma on it, you need to double quote the path. For this answer, I based on what I read here:
Open folder which contains comma in its path

Using strings for network path, not mapped drive, with Shell in VBA

QUESTION UPDATED, PLEASE SEE BELOW
I am trying to use string variables (exedir - the full network drive directory of an exe file, and inputdir - the location of the input file argument) to launch an exe with its argument using shell in VBA.
The commented out line in the script below does not work. If I manually set the drive using a letter I can get it to work, as shown below, but the .exe and .lam input file used here are both on networked drives (the variable comp is the unique name of the users PC, which sets the name of the .lam input file, so the input file name is different for every user).
I'm not too familiar with the syntax and borrowed it from elsewhere. Am I missing a quotation mark or maybe have too many in the commented out row?
Sub CallExeWithInput()
Set wsh = VBA.CreateObject("WScript.Shell")
'Statusnum = wsh.Run(Command:="""" & exedir & """""""" & inputdir & """""", windowstyle:=1, waitonreturn:=False)
SetCurrentDirectory "M:\path\"
Statusnum = wsh.Run(Command:="foo.exe ""M:\path\" & comp & ".lam""", windowstyle:=1, waitonreturn:=False)
End Sub
Example of exedir: \\network\path\foo.exe
Example of inputdir: \\network\path\compname.lam
Example of comp: compname << found using Environ$("computername")
I'm aware of some previous questions, having read many to get this far.
I don't want to provide the letter of the drive, and ideally want to launch the .exe with the input file using string variables to input everything. One major reason I want to only use strings, is that they can be controlled by a single variable, and when the directory changes (say with an upgrade of the .exe) it will be easy to update this script.
UPDATE
Following the comments kindly provided below I arrived here:
SetCurrentDirectory fldr
Statusnum = wsh.Run(Command:="foo.exe " & quote & inputdir & quote, windowstyle:=1, waitonreturn:=False)
Where quote = chr(34) and fldr = \\network\path\
Interestingly, if inputdir is defined as a path to a lettered drive (inputdir = M:\etc), this works. If it is to a network drive path (inputdir = \\network\etc), it launches but the .exe immediately crashes with an invalid floating point operation.
How can I alter this so the input file can be provided as a network path?
If this is not possible I will presumably need a subroutine that locates which letter the user has mapped the network drive onto in order to build my string, such as this:
path = ":\foo\bar\"
dim x as integer
for x = 65 to 90
If CBool(Len(Dir(Chr(x) & path))) Then
msgbox "It's in drive " & Chr(x)
exit for
end if
next x

Open a PDF from Excel with VBA in Google Chrome on a specific page

I am creating a macro in Excel that should open a PDF document on a specified page with chrome.
Generally, the opening part works. My problem is that when I add the page number (e.g. #page=15) to the url, the shell encodes the "#" symbol into "%23", which Chrome is not able to interpret correctly (file not found).
Here is my code
'The path to the file, replaces spaces with the encoding "%20"
Path = Replace((filePath& "#Page=" & iPageNum), " ", "%20")
Dim wshShell, chromePath As String, shellPath As String
Set wshShell = CreateObject("WScript.Shell")
chromePath = wshShell.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe\")
shellPath = CStr(chromePath) & " -url " & Path
If Not chromePath = "" Then
'how I first tried it:
Shell (shellPath)
'for testing purposes, led to the same result though:
Shell ("""C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"" ""C:\Users\t.weinmuellner\Desktop\Evon\PDF Opening\PDFDocument.pdf#page=17""")
End If
Is there a different way to do this with Chrome? I haven't found anything that reads the installation path dynamically.
You just need to specify the protocol file:/// if you want to load files from the local hard disk. Then # gets not translated into %23.
Shell ("""C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"" ""file:///C:\Users\t.weinmuellner\Desktop\Evon\PDF Opening\PDFDocument.pdf#page=17""")
If Adobe Acrobat Reader is installed on the system I would suggest to use the funcion openPDF from Daniel Pineault. This will open the file in Adobe Reader directly. You can find the source code of the function here
A test could look like that
Sub TestSO()
Dim fileName As String
Dim pageNo As Long
fileName = "Path and filename of PDF"
pageNo = 20
OpenPDF fileName, 20
End Sub

Execute shell is not opening up file provided as string

I am trying to solve an error in code written by someone else. The shell function running in an MS Excel VBA environment is as follows:
Public Function ExecCmd(cmdline$)
Dim proc As PROCESS_INFORMATION
Dim start As STARTUPINFO
Dim ret&
' Initialize the STARTUPINFO structure:
start.cb = Len(start)
' Start the shelled application:
ret& = CreateProcessA(vbNullString, cmdline$, 0&, 0&, 1&, _
NORMAL_PRIORITY_CLASS, 0&, vbNullString, start, proc)
' Wait for the shelled application to finish:
ret& = WaitForSingleObject(proc.hProcess, INFINITE)
Call GetExitCodeProcess(proc.hProcess, ret&)
Call CloseHandle(proc.hThread)
Call CloseHandle(proc.hProcess)
ExecCmd = ret&
End Function
The cmdline$ input is: "excel.exe W:\L\BDTP\Products\Mandate FS\OfferToolUpdate.xlsm"
When I run the code it opens another excel instance and attempts to open a file under "W:\L\BDTP\Products\Mandate.xlsx"... after two more error messages it tells me that it can also not find "FS\OfferToolUpdate.xlsm"
Clearly this error is produced some how due to the space in the naming convention of the Folder the file resides in.
How can I open the file without changing the folder name?
I believe you used example as shown at: https://support.microsoft.com/en-us/kb/129796 ...
Just update execution line to wrap out the file:
ExecCmd "excel.exe ""U:\ADMINISTRATION\Expenses\Some File.xlsx"""
I have found a viable workaround for the time being, though I'm sure there are more professional ways of going about it. I have changed the input command line to be in extra quotes:
"""" & "excel.exe W:\L\BDTP\Products\Mandate FS\OfferToolUpdate.xlsm" & """"

Can an Excel macro pull output from a command line directly into a sheet?

I have a VBA macro that executes a Command Line function to create a text file listing the files in a directory; however, instead of copying and pasting/importing the list from the text file to the worksheet, is it possible to simply have the putput of the command line be passed directly into the worksheet?
The VBA code I am working with right now to create the file is:
CMD = "DIR /A:-D-H /O:-D-G /B \\directory\* > \\sleuth.txt"
Shell "cmd.exe /c " & CMD
I much appreciate any ideas on this front!
You can save it to a string variable using this class. (Direct download link here.)
Here's an example usage:
Sub Test()
Dim cls As New clsRunApp
Dim s As String
cls.command = "cmd.exe /k dir"
s = cls.RunAppWait_CaptureOutput
Set cls = Nothing
MsgBox (s)
End Sub
From there, you can output it to your worksheet directly.

Resources