Excel VBA Shell "file not found" - vba

For the life of me, I can't get this shell procedure to work with variables. I'm trying to execute POSTRESULTS6 which then processes the csv file. The "DISPLAY" argument tells POSTRESULTS6 to show a progress window as it processes the csv.
Dim MyAppID As Variant
Dim stExecute As String: stExecute = """C:\Program Files (x86)\PerkinElmer\LABWORKS64\POSTRESULTS6.exe"""
Dim stFile As String: stFile = "INFILE:C:\PostResult6\Multi-Component_Data_Import.csv"
Dim stFull As String: stFull = "stExecute & "" "" & stFile"
MyAppID = Shell("stFull" & "" "" & DISPLAY, vbNormalFocus)
AppActivate (MyAppID)
The procedure works as expected when I type it all out in one single line like this:
MyAppID = Shell("""C:\Program Files (x86)\PerkinElmer\LABWORKS64\POSTRESULTS6.exe"" & "" "" & INFILE:C:\PostResult6\Multi-Component_Data_Import.csv" & "" "" & DISPLAY, vbNormalFocus)
The reason that I want to use variables is to shorten the lines of code and possibly make the procedure dynamic for the csv file name.
I'm guessing that it has something to do with spaces but I can't figure out where my mistake is. I also can't figure out how to continue the long string of code to the next line. The space-underscore doesn't seem to work.
As an aside, when my shell procedure was very simple, I didn't have to declare the MyAppID variable. As it got more complex, I started getting errors about MyAppID not being defined. Does anyone know why this is?
Any help is greatly appreciated.
Edit: The Error that I get when I run the code with variables is "Run-time error '53': File not found"
I know that the file paths assigned to the variables are correct. I tested them in windows explorer.

Your problem is, for example: stFull = "stExecute & "" "" & stFile"
You have stExecute within quotes which makes it a literal not a variable.
I think this is correct:
Dim MyAppID As Variant
Dim stExecute As String: stExecute = """C:\Program Files (x86)\PerkinElmer\LABWORKS64\POSTRESULTS6.exe"""
Dim stFile As String: stFile = "INFILE:C:\PostResult6\Multi-Component_Data_Import.csv"
Dim stFull As String: stFull = stExecute & " " & stFile
MyAppID = Shell(stFull & " DISPLAY", vbNormalFocus)

You've got messed up quotes. stFull in your last line is being evaluated as a literal not as a string. Here's my attempt to solve your quotes debacle.
Dim stExecute As String: stExecute = "C:\Program Files (x86)\PerkinElmer\LABWORKS64\POSTRESULTS6.exe"
Dim stFile As String: stFile = "INFILE:C:\PostResult6\Multi-Component_Data_Import.csv"
Dim StFull As String
StFull = """" & """" & """" & stExecute & """" & """" & " & """" """" & " & stFile & """"
MyAppID = Shell(stFull & "" "" & DISPLAY, vbNormalFocus)
AppActivate (MyAppID)
Outputting StFull:

My perspective for using variables in Shell:
MyAppID as variant
Dim Program as string
Dim File as string
Program = """Your path to program"""
File = """Your path to file"""
MyAppID = Shell(Program & " " & File, vbNormalFocus)
Additional comments:
Single quotes can be used (e.g. Program = "Your path to program") but then VBA may have problem to compile properly if you have spaces in folders names and would return an error.

Related

More efficient way to write command prompts in VBA?

My macro for Word highlights specific words from a specified list for each document in a folder. At the end of the macro, I would like to append the names of each of these files to include "_Highlight" using the command line. I am not too familiar with using the Command Prompt in VBA, so my code ended up being messy.
I am trying to replicate the following command prompt in VBA.
for %a in (“C:\path\*.docx*”) do ren “%~a” “%~Na_Highlight%~Xa”
For the actual file path, I select a folder in FileDialog and store it in a variable to be used in the command prompt, strShellFldr. I am having some trouble concatenating all pieces of the code, especially with special characters, spaces, and quotation literals.
Here is what I tried:
The code below runs just fine, however it seems quite cumbersome. Is there a more efficient way to write this?
Shell.Run "cmd.exe /c" & "for %a in" & Chr(32) & "(" & Chr(34) & strShellFldr & Chr(34) & ")" & Chr(32) & "do ren" & Chr(32) & Chr(34) & "%~a" & Chr(34) & Chr(32) & Chr(34) & "%~Na_Hilight%~Xa" & Chr(34)
Is there a native VBA function that allows you to append a file name maybe?
Thank you for your help and my apologies for posting some wretched code on here.
This piece of VBA code can loop through a list of files in a given folder as input, and add "_Highlight" at the end of the name, just before the file extension:
example:
MyFile.txt --> MyFile_Hightlight.txt
Public Sub RenameFiles(Folder As String)
Dim oFSO As Scripting.FileSystemObject
Dim oFolder As Scripting.Folder
Dim oFile As Scripting.File
Dim ext As String
Dim Name As String
On Error GoTo ERROR_TRAP
Set oFSO = New Scripting.FileSystemObject
Set oFolder = oFSO.GetFolder(Folder)
For Each oFile In oFolder.Files
ext = Split(oFile.Name, ".")(UBound(Split(oFile.Name, ".")))
Name = Left$(oFile.Path, Len(oFile.Path) - Len(ext) - 1)
oFSO.MoveFile Name & "." & ext, Name & "_Highlight" & "." & ext
Next oFile
Set oFSO = Nothing
Set oFolder = Nothing
Set oFile = Nothing
Exit Sub
ERROR_TRAP:
Debug.Print "ERROR : RenameFiles (" & oFolder.Name & ")"
End Sub
Do not forget to add Microsoft Scripting Runtime reference first in your VB Editor.

Compare two For Each lists in vb.net

I have a small problem.
I have two for each routines. One gives me all foldernames in the current folder. The other gives me all window names opened. Both are saving the results in a String. One with newlines, the other with ~, so I can loop through both and get all the items one by one.
This is the part:
Dim Folders As String
For Each Dir As String In System.IO.Directory.GetDirectories(My.Computer.FileSystem.CurrentDirectory & "\Data\")
Dim dirInfo As New System.IO.DirectoryInfo(Dir)
Folders = Folders & dirInfo.Name & "~"
Next
Dim FolderList() As String = Folders.Split("~")
Dim p As Process
Dim Windows As String
For Each p In Process.GetProcesses
Windows = Windows & vbNewLine & p.MainWindowTitle.ToString
Next
Windows = LineTrim(Windows)
This works. But now, I want to compare them.
I only want to get the Folders, where a window exists, which contains the foldername.
For example, I have 3 folders: Test1,Test2,Test3.
I have one Window opened: "Test1 - Window"
Now I only want to get "Test1" as Result once.
I got it working so far, but I get "Test1" 3 times, because there are 3 folders. Because I am creating new Windows by this info, my function spams new windows..
This is the whole function:
Dim Folders As String
For Each Dir As String In System.IO.Directory.GetDirectories(My.Computer.FileSystem.CurrentDirectory & "\Data\")
Dim dirInfo As New System.IO.DirectoryInfo(Dir)
Folders = Folders & dirInfo.Name & "~"
Next
Dim str As String() = Folders.Split("~")
For Each Folder As String In str
If (My.Computer.FileSystem.FileExists(My.Computer.FileSystem.CurrentDirectory & "\Data\" & Folder & "\" & "Status.txt")) Then
Dim StartTime As String = Inireader.WertLesen("Settings", "StartTime", My.Computer.FileSystem.CurrentDirectory & "\Data\" & Folder & "\Time.ini")
Dim StopTime As String = Inireader.WertLesen("Settings", "StopTime", My.Computer.FileSystem.CurrentDirectory & "\Data\" & Folder & "\Time.ini")
If (IsInTime(StartTime, StopTime) = True) Then
Dim p As Process
Dim Windows As String
For Each p In Process.GetProcesses
Windows = Windows & vbNewLine & p.MainWindowTitle.ToString
Next
Windows = LineTrim(Windows)
Dim Ar() As String = Split(Windows, Environment.NewLine)
For Each Window As String In Ar
If sX.ToString.Contains(Window & " - python " & My.Computer.FileSystem.CurrentDirectory & "\Data\" & Window& "\" & Window & ".py") Then ''''The Spam cause line
Else
Dim Path = My.Computer.FileSystem.CurrentDirectory & "\Data\" & Folder & "\" & Folder & ".py"
Dim startInfo As New ProcessStartInfo
startInfo.FileName = "cmd.exe"
startInfo.Arguments = "/k " & "title " & Folder & " & python " & Path
startInfo.WorkingDirectory = My.Computer.FileSystem.CurrentDirectory & "\Data\" & Folder & "\"
Process.Start(startInfo)
End If
Next
End If
End If
Next
I can´t shorten it very much..
Could you help me out?
Thank you :)
Best regards!

Ms Access Get filename with wildcards or loop

I am using MS Access Forms and I am trying to open a file but don't know how to open the file based knowing only part of the name. Example below works
Private Sub Open_Email_Click()
On Error GoTo Err_cmdExplore_Click
Dim x As Long
Dim strFileName As String
strFileName = "C:\data\office\policy num\20180926 S Sales 112.32.msg"
strApp = """C:\Program Files\Microsoft Office\Office15\Outlook.exe"""
If InStr(strFileName, " ") > 0 Then strFileName = """" & strFileName & """"
x = Shell(strApp & " /f " & strFileName)
Exit_cmdExplore_Click:
Exit Sub
Err_cmdExplore_Click:
MsgBox Err.Description
Resume Exit_cmdExplore_Click
End Sub
If I change the strFilename to being
strFileName = "C:\data\" & Me.Office & "\" & Me.nm & " " & Me.pol & "\" & "*"& " S Sales " & Me.amt & "*" & ".msg"
It includes the * rather than using it as a wildcard, the date/numbers can be anything or in another format but always eight numbers. I tried using a while loop on the numbers but I am not sure the best way of doing this sorry.
You can use the Dir function to iterate over all files that match a string pattern.
strApp = """C:\Program Files\Microsoft Office\Office15\Outlook.exe"""
Dim strFilePattern As String
strFilePattern ="C:\data\" & Me.Office & "\" & Me.nm & " " & Me.pol & "\" & "*"& " S Sales " & Me.amt & "*" & ".msg"
Dim strFileName As String
strFileName = Dir(strFilePattern)
Do While Not strFileName = vbNullString
If InStr(strFileName, " ") > 0 Then strFileName = """" & strFileName & """"
x = Shell(strApp & " /f " & strFileName)
strFileName = Dir
Loop
The first call to Dir with the pattern as a parameter will find the first file that matches the pattern supplied. All subsequent calls without the pattern will return the next file that matches the pattern.
So, lets rebuild the question a bit. Imagine that you are having the following 5 files in a given folder:
A:\peter.msg
A:\bstack.msg
A:\coverflow.msg
A:\heter.msg
A:\beter.msg
and you need to find the files, that correspond to "A:\*eter.msg" and print them.
For this, you need to use the keyword Like:
Sub TestMe()
Dim someNames As Variant
someNames = Array("A:\peter.msg", "A:\bstack.msg", _
"A:\coverflow.msg", "A:\heter.msg", "A:\beter.msg")
Dim cnt As Long
For cnt = LBound(someNames) To UBound(someNames)
If someNames(cnt) Like "A:\*eter.msg" Then
Debug.Print someNames(cnt)
End If
Next
End Sub
Loop through files in a folder using VBA?

VBA Access CSV import issue from netdrive using shell

I have an issue which i can't figure out.
Quest is to import csv file from a netdrive.
In a basic version files to import were selected automaticaly by code:
Function FilesAfterDate(Directory As String, FileSpec As String, AfterDate As Date) As String()
'Requires a reference to the Microsoft Scripting Runtime object lib
Dim oFS As New FileSystemObject, oFile As File
Dim listFiles() As String
Dim i As Long
i = 0
If Right(Directory, 1) <> "\" Then Directory = Directory & "\"
For Each oFile In oFS.GetFolder(Directory).files
If oFile.DateLastModified > AfterDate And oFile.Name Like FileSpec Then
ReDim Preserve listFiles(i)
listFiles(i) = oFile.Name
i = i + 1
End If
Next
FilesAfterDate = listFiles
End Function
And then it was imported by code (for each Importfiles(i) where ImportReport = fullpath of Importfiles(i))
DoCmd.TransferText acImportDelim, "ImpSpec_" & sObjSpec & "Csv", "tb" & sObjName & cloneTableNameDesc, ImportReport, False
This solution works really slow, so with the help of the users of this portal I've created a shell import:
fileDetails = Split(CreateObject("wscript.shell").exec("cmd /c pushd " & Chr(34) & source_path & Chr(34) & " & forfiles /S /D +" & s_data & " & popd").StdOut.ReadAll, Chr(10))
and if I use same import command where ImportReport = fullpath of fileDetails (i) i get an error number 31519.
I used debug.print to check all vartypes, path etc and they are all the same. However sollution with shell doesn't work... Any idea for the reason why?
SOLVED:
As I figure it out - splitting shell function to array somehow doesn't have right data/names for access.
It worked when instead of splitting the shell function i've just assigned it to string value
full_string_paths = CreateObject("wscript.shell").exec("cmd /c pushd " & Chr(34) & source_path & Chr(34) & " & forfiles /S /D +" & s_data & " & popd").StdOut.ReadAll
and then using Mid function and Instr I've created an array of correct filename's
After that everything worked perfectly.

vb.net pass folder path as commandline argument

I'm trying to pass a folder path via commandline argument to an application.
Problem: my folder path contains space " " in it's string. When I read the commandline arguments in the application I get my path chopped into pieces on the space " "
Sub Main()
Dim arguments As String() = System.Environment.GetCommandLineArgs()
For Each Arg As String In arguments
Console.WriteLine("Argument : " & Arg)
Next
Console.ReadLine()
End Sub
Edit: added code to build my argument
Private Sub btn_Copy_Click(sender As Object, e As EventArgs) Handles btn_Copy.Click
Dim args(3) As String
args(0) = """" & tb_CopyFromPath.Text & """"
args(1) = """" & tb_CopyToPath.Text & """"
args(2) = """" & tb_ItemTag.Text & """"
args(3) = """" & tb_Prefix.Text & """"
Dim argument As String
argument = args(0) & " " & args(1) & " " & args(2) & " " & args(3)
Process.Start("J:\VB.NET - EM AddIn\EM_Design_AddIn\CopyDesign\bin\Debug\CopyDesign.exe", argument)
End Sub
This result isn't okay. The first argument of the first path now contains a piece of the second path.
Edit: add value result from debug.
"""C:\VaultWorkspace\cadcampc\03-Vessel configurator - R2.0\Nozzles\WN_RF_ASME_B16.5\"" ""C:\VaultWorkspace\cadcampc\03-Vessel configurator - R2.0\Test Copy Design\N03"" ""N3"" ""12345-3"""
It is very simple. Just use ".
If you pass test test test parameters, you'll get 3 arguments. But if you write test "test test", you'll receive two parameters: test and test test.
Just pass it with double-quotes around it.
I.e:
app.exe "C:\Sub folder 1\Sub folder 2"
If you do it in code:
Process.Start("app.exe", """" & path & """")
The quotes specifies the start and end of an argument.
EDIT:
In your case you could do this instead:
argument = """" & args(0) & """ """ & args(1) & """ """ & args(2) & """ """ & args(3) & """"
Use CHR(34) to delimiter a string with spaces within.
See my answer here:
vb.net How to pass a string with spaces to the command line