0

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

Sub RunExe()
    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 Long
    errorCode = wsh.Run("C:\dir\dir\dir\dir\dir\dir\dir\dir\dir\My.exe", windowStyle, waitOnReturn)
End Sub

The issue I am having is that the cmd line already starts in a folder with a different path. So when I run this code it starts down a path that I know the program is not in, I get the error:

Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path 
'C:\dir\dir\dir\dir\dir'.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.Directory.SetCurrentDirectory(String path)
   at ReadDirectory(String directory)
   at Program.Main(String[] args)

Is there some way to start back at c:\users? Or clear/flush the stream? This is where running run -> cmd.exe starts. But for some reason I have some memory in vba and starts in a different file path.

chris neilsen
  • 52,446
  • 10
  • 84
  • 123
  • _where running run -> cmd.exe starts_ is the Windows current directory. You can change that using `ChDir`, eg `ChDir "C:\dir\dir\dir\dir\dir\dir\dir\dir\dir` – chris neilsen Oct 26 '20 at 22:52
  • 1
    I suspect that's not a realistic path to your executable. By chance does the _real_ path have spaces and therefore require quotation marks or escape characters? – Marc Oct 26 '20 at 22:53
  • no spaces or weird characters. Easy enough to verify my path by running cmd from start and navigating along the path I have specified. but given the starting point that it has when i run it form vba, I have to go back 2 folders then forward. I don't know how to put in cd ..\ commands in the shell from vba either. I don't know if it will always start from that random file path either. – user3281977 Oct 26 '20 at 23:17
  • @chrisneilsen I cannot get ChDir to compile in your example. I have tried Call Shell("cmd ChDir C:\Users", vbNormalFocus), but this doesn't do anything I expect. – user3281977 Oct 26 '20 at 23:27
  • 1
    It's a VBA command - so it exactly and only `ChDir "C:\dir\dir\dir\dir\dir\dir\dir\dir\dir"` (ie doesn't use Shell) – chris neilsen Oct 26 '20 at 23:42
  • @chrisneilsen OOOHHH Eureka! – user3281977 Oct 26 '20 at 23:58

0 Answers0