I want to open a batch file via vba. This always was no problem but lately the path is not correct.
The path is always:
C:\Users\ [username] \Documents>
The batch file itself seems to be found because the code is correctly passed through:
e.g. C:\Users[username]\Documents>echo ...
I tried with absolute and with relative path. Both leads to the same problem.
pathDir = ThisWorkbook.Sheets("Info").Range("B1").Value
...
functionPath = pathDir & "\" & paramFunction & ".bat"
Call ShellExecute(0, "open", functionPath, paramECU & " " & paramBackend & " " & paramVIN, "", SW_SHOW)
What could be the problem?
Default shell path of excel is
C:\Users[username]\Documents
So, in vba you can check by using the code
msgbox CurDir
If you need to change path of shell, the command is
ChDir "C:\Desire Path"
In case of you is
ChDir pathDir
If the path is in other drive (not C:) you should change drive before change directory. For example drive D:.
ChDrive "D"
ChDir "D:\Desire Path"
then call ShellExecute without prefix path.
Related
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
so i searched but didnt find something good for my use , i have a folder where i will import an excel file , this excel file will have a different name everytime how i can open it with vba , thank you
You can get the file name using the Dir function and multiple character (*) wildcard.
Const Path As String = "C:\Test"
Dim filename As String
filename = Dir(Path & "\*.xlsx")
If Len(filename) > 0 Then
' Do your work
' Remember 'filename' only holds the file name
' you will need to attach the rest of the path to get the full directory.
End If
Note: If there's only one file in the folder you will not have any issues, however if the folder contains multiple files (matching the above pattern), you will need to either loop or provide additional file name characters to the function.
An example:
File name: daily_report_20190404.xlsx
filename = Dir(Path & "\daily_report_*.xlsx")
Hope this helps.
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
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
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