shell command using variable with spaces - vba

Public Sub test()
Dim path As String
path1 = "C:\File Folder\File Test.pdf"
path2 = "C:\FileFolder\FileTest.pdf"
Shell "C:\Program Files (x86)\Nuance\PDF Professional 8\bin\GaaihoDoc.exe " & path1, vbNormalFocus
End Sub
The above code in VBA works if the path2 variable is used instead of path1, because of the spaces in the path1 variable. How can it be fixed to run the variable path1?

Paths with spaces need to be quoted with double-quotes.
Escape the quotes by doubling them up:
path1 = "C:\File Folder\File Test.pdf"
Shell """C:\Program Files (x86)\Nuance\PDF Professional 8\bin\GaaihoDoc.exe"" """ & path1 & """", vbNormalFocus

Related

Check right installation of 7-Zip (64 / 32bit)

My goal is avoid error msg from VBA debugger. Need to check which version of 7-zip have installed, program files/ or program files (x86):
Trying do simple "IF" function.
Dim PathZipProgram As String
strCommand As String
PathZipProgram = "C:\Program Files(x86)\7-Zip\7z.exe"
If Right(PathZipProgram, 1) Then
PathZipProgram = PathZipProgram
Else
PathZipProgram = "C:\Program Files\7-Zip\7z.exe"
End If
Shell strCommand
strCommand = """" & PathZipProgram & """ a -tzip """
VBA cant find 7zip.
You can check if the file exist with a function like this:
Function FileExists(FilePath As String) As Boolean
Dim TestStr As String
TestStr = ""
On Error Resume Next
TestStr = Dir(FilePath)
On Error GoTo 0
If TestStr = "" Then
FileExists = False
Else
FileExists = True
End If
End Function
And then use it in your code:
Dim PathZipProgram As String
Dim strCommand As String
PathZipProgram = "C:\Program Files(x86)\7-Zip\7z.exe"
If Not FileExists(PathZipProgram) Then
PathZipProgram = "C:\Program Files\7-Zip\7z.exe"
End If
Shell strCommand
strCommand = """" & PathZipProgram & """ a -tzip """
Hope this help as a starting point.
Installation Path: 7-Zip could be installed in another disk location (for example the D: drive, or somewhere else). You do
need to read the paths from the registry to be sure. A couple of
suggestions below:
1. Hacky Version
I have put a full script below to use, but you can essentially get what you want the hacky way (make sure the paths actually exists - obviously - maybe use "C:\Program Files\7-Zip" if there are problems seen):
Check File Exists:
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists("C:\Program Files (x86)\7-Zip\7z.exe")) Then
' Do Stuff
End If
Get File Version:
Set fso = CreateObject("Scripting.FileSystemObject")
MsgBox fso.GetFileVersion("C:\Program Files (x86)\7-Zip\7z.exe")
Don't rely on this please. It will fail eventually. Please see below.
2. Full Version
Here is a full version, the steps you need to make something that has a hope to be reliable. Essentially read paths from registry and take it from there:
Const HKEY_LOCAL_MACHINE = &H80000002 : strComputer = "."
Set fso = CreateObject("Scripting.FileSystemObject")
Set reg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\default:StdRegProv")
' 64-bit - Read 7-zip installation path from registry
regpath64 = "SOFTWARE\7-Zip"
reg.GetStringValue HKEY_LOCAL_MACHINE, regpath64, "Path64", regvalue64
fullpath64 = regvalue64 + "\" + "7z.exe"
If (fso.FileExists(fullpath64)) Then
MsgBox "7-zip 64-bit: " + fso.GetFileVersion(fullpath64), vbOKOnly, "64-bit:"
End If
' 32-bit - Read 7-zip installation path from registry
regpath32 = "SOFTWARE\WOW6432Node\7-Zip"
reg.GetStringValue HKEY_LOCAL_MACHINE, regpath32, "Path", regvalue32
fullpath32 = regvalue32 + "\" + "7z.exe"
If (fso.FileExists(fullpath32)) Then
MsgBox "7-zip 32-bit: " + fso.GetFileVersion(fullpath32), vbOKOnly, "32-bit:"
End If
Disclaimer: For the 64-bit registry read: there could be a Path and a Path64 entry
(I have both). Not sure what earlier and / or later versions will
have. Please check.

Calling a Variable on the Command Line in VBA

I have a variable in my VBA script and I'm trying to call that variable on the command line within the script.
Sub Test()
'Set enviro to %APPDATA%
Dim enviro As String
enviro = CStr(Environ("APPDATA"))
'Create a new variable that sets the file path for the RepoDir.txt
RepoPath = enviro & "\RepoDir.txt"
'Create a new variable to grab the line of text in RepoDir.txt
Dim FilePath As String
Dim strFirstLine As String
'The new variable calls the RepoPath Variable
FilePath = RepoPath
Open FilePath For Input As #1
Line Input #1, strFirstLine
'MsgBox (strFirstLine)
Shell ("cmd /c cd call strFirstLine & git pull RandomSig > %TEMP%\gitPull.txt 2>&1")
End Sub
I am trying to call the variable strFirstLine which contains a a pathway I want the command line to read and then CD to it. Is there anyway to do this?
Thank you!
You will want to pass the value of strFirsLine, not the name. Use (example):
Shell ("cmd /c cd " & strFirstLine & "git ..."

Pass parameter\variable from .vbs to .bat

I'm trying to pass a variable from a VBS to BAT but i'm getting "The system cannot find the file specified"
Here is my vbs :
Option Explicit
Dim strFile
strFile = SelectFile( )
If strFile = "" Then
WScript.Echo "No file selected."
Else
WScript.Echo """" & strFile & """"
End If
Function SelectFile( )
Dim objExec, strMSHTA, wshShell
SelectFile = ""
strMSHTA = "mshta.exe ""about:" & "<" & "input type=file id=FILE>" _
& "<" & "script>FILE.click();new ActiveXObject('Scripting.FileSystemObject')" _
& ".GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);" & "<" & "/script>"""
Set wshShell = CreateObject( "WScript.Shell" )
Set objExec = wshShell.Exec( strMSHTA )
SelectFile = objExec.StdOut.ReadLine( )
Dim wshShelll
Set WshShelll = Wscript.CreateObject("WScript.Shell")
WshShelll.Run "C:\Users\nbendjelida\Desktop\email.bat" & SelectFile
Set objExec = Nothing
Set wshShell = Nothing
Set wshShelll = Nothing
End Function
here is my bat :
"C:\Program Files\Microsoft Office\Office12\Outlook.exe" /eml %1
do you have any idea ?
I repeat the right answer of sachadee with more details to get this question removed from the list of unanswered questions.
Run Method must be called with first parameter being the command to execute with the parameters exactly as when entering the command in the command line window. The examples on the referenced Microsoft help page have also a space character after the command Notepad.
The command line required to call the batch file with a file name as first parameter is:
C:\Users\nbendjelida\Desktop\email.bat name_of_selected_file
But the Windows script host code line
WshShelll.Run "C:\Users\nbendjelida\Desktop\email.bat" & SelectFile
builds the string for the command to run as
C:\Users\nbendjelida\Desktop\email.bat name_of_selected_file
because of the missing space character.
The problem is solved with the correct Windows script host code line
WshShelll.Run "C:\Users\nbendjelida\Desktop\email.bat " & SelectFile
because of the space charater between name of batch file and name of selected file.
If name of selected file contains 1 or more spaces, it is necessary that either variable SelectFile contains already a double quote at beginning and at end, or the necessary double quotes are added on concatenating the command string.
Example with entire batch file name also containing a space character:
Dim FileName
FileName = "%TEMP%\Any File.txt"
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run """%USERPROFILE%\Desktop\My Batch File.bat"" """ & FileName & """"
The batch file My Batch File.bat on desktop of current user containing
#echo %0 %*
#pause
outputs for example on Windows 7
"C:\Users\username\Desktop\My Batch File.bat" "C:\User\username\AppData\Local\Temp\Any File.txt"
or on English Windows XP
"C:\Documents and Settings\user name\Desktop\My Batch File.bat" "C:\Documents and Settings\user name\Local Settings\Temp\Any File.txt"
which are the expected results for the command string.
(Yes, a user name can contain a space character although Microsoft recommends not to use a space character in user name, see Microsoft page Creating User and Group Accounts.)

Winzip not executing with gap in file path

I've used the code from Extract all .gz file in folder using VBA Shell command, to extract .gz files.The problem is that if there is a gap in the filepath, code doesn't work, if there is no gap, it works, as illustrated below:
Notice in first example, there is no '_' but a gap ' ', between 'K' and 'L', therefore file path has gaps,
whereas example that works, there is an '_', and the whole filepath has no gaps
'Example that doesn't work:
Sub extractAllFiles()
Dim MyObj As Object, MySource As Object, File As Variant
Dim shellStr As String
File = Dir("Z:\A_B_C\D_E_F\G_H_I\J_K L\_M_N_O\P_Q_R\*.gz")
While (File <> "")
If InStr(1, File, ".gz") > 0 Then
shellStr = "C:\Program Files\WinZip\winzip32 -e Z:\A_B_C\D_E_F\G_H_I\J_K L\_M_N_O\P_Q_R\" & File & " Z:\A_B_C\D_E_F\G_H_I\J_K L\_M_N_O\P_Q_R\"
Call Shell(shellStr, vbHide)
End If
File = Dir
Wend
End Sub
'Example that works:
Sub extractAllFiles()
Dim MyObj As Object, MySource As Object, File As Variant
Dim shellStr As String
File = Dir("Z:\A_B_C\D_E_F\G_H_I\J_K_L\_M_N_O\P_Q_R\*.gz")
While (File <> "")
If InStr(1, File, ".gz") > 0 Then
shellStr = "C:\Program Files\WinZip\winzip32 -e Z:\A_B_C\D_E_F\G_H_I\J_K_L\_M_N_O\P_Q_R\" & File & " Z:\A_B_C\D_E_F\G_H_I\J_K_L\_M_N_O\P_Q_R\"
Call Shell(shellStr, vbHide)
End If
File = Dir
Wend
End Sub
I want the first example to work, but why doesn't it?
There are no errors. The code runs, opens winzip, but it's empty, no file is unzipped!
Many thanks.
Try putting quotation marks around the paths in your shell string:
shellStr = "C:\Program Files\WinZip\winzip32 -e ""Z:\A_B_C\D_E_F\G_H_I\J_K L\_M_N_O\P_Q_R\" & File & """ ""Z:\A_B_C\D_E_F\G_H_I\J_K L\_M_N_O\P_Q_R\"""
In case you didn't already know, two double quotes ("") evaluates to a single double quote inside the string. Compare to languages like C where the backslash would be used to escape the quotation mark (\").

Finding txt File path dynamically

I need to read a txt file but I don't have the path. The text file is two directories before the path of the script I'm running. I thought I could use "WScript.ScriptFullName" and then just use an instrRev and make it split the str at "/". But It doesn't work Could you guys help me with that. I have to run this on multiple computers so the path changes but the text file will always be two derictories above the script path
My code so far
Dim strScriptPath
strScriptPath = Replace(WScript.ScriptFullName, WScript.ScriptName, "")
WScript.Echo strScriptPath
WScript.Echo(WScript.ScriptFullName)
Dim DashRev
DashRev = instrRev(WScript.ScriptFullName, "/")
wscript.echo DashRev
First replace the "/" with "\"
Then try the following. This seems to work for me:
Dim strScriptPath
strScriptPath = Replace(WScript.ScriptFullName, WScript.ScriptName, "")
WScript.Echo strScriptPath
WScript.Echo(WScript.ScriptFullName)
Dim first, sec
first = instrRev(strScriptPath, "\",Len(strScriptPath)-1)
sec = instrRev(WScript.ScriptFullName, "\",first-1)
wscript.Echo "parent = " & Left(strScriptPath,sec)
The idea being that strScriptPath is always going to end in "\" and first is going to exclude that from the instrrev by using the starting position of one less than the length of the path. Same thing essentially with sec.
Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
WScript.Echo FSO.GetFile(WScript.ScriptFullName).ParentFolder.ParentFolder.ParentFolder.Path