VBA execute function with several quotation marks in parameters cmd.exe - vba

Here is a syntax error. How to properly run the ShellWait function? I care about double quotes being used. The boolean parameter should be able to be changed to false. I do not use VBA every day so I am asking for an example if you can.
Sub ShellWait(fName As String, Optional showWindow As Boolean = True)
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
wsh.Run fName, -showWindow, True
End Sub
Private Sub Document_close()
ShellWait "cmd /c echo ^<meta http-equiv="x-ua-compatible" content="IE=10"^> && echo '"hello"' "
' ^the above code does not work
ShellWait "cmd /c echo '"hello"' "
' ^the above code does not work, syntax error
ShellWait (cmd /c echo '"hello"')
' ^the above code does not work, syntax error
End Sub

You could use the following
ShellWait "cmd /K echo ^<meta http-equiv=""x-ua-compatible"" content=""IE=10""^> && echo '""hello""' "

Related

Shell console command in VBA Access doesn't work properly

I have a big issue with my code, which i'vre created by using already known/someone solution.
What's going on:
I need a code which will give me an extract of all files, which lastDateModified is older than some specific date. However the best solution will be if i will received those file names in array (don't know how to do that"
Problem:
When I enter a command in the console, it gives me the list of files correctly.
Whereas when I place it in Access it gets me text:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
I:\Documents\Access>
Code:
Public Sub TestCommandLine()
Const lngCancelled_c As Long = 0
Dim strCmd As String
strCmd = "cmd.exe forfiles /P directory /S /D +01/04/2015) > directory2"
CommandLine strCmd, False
End Sub
Public Function CommandLine(command As String, Optional ByVal keepAlive As _
Boolean = False, Optional windowState As VbAppWinStyle =
VbAppWinStyle.vbHide) _
As Boolean
'--------------------------------------------------------------------------------
' Procedure : CommandLine
' Author : Aaron Bush (Oorang)
' Date : 10/02/2007
' Purpose : Provides a simple interface to execute a command lines from VBA.
' Input(s) :
' command : The DOS command you wish to execute.
' keepAlive : Keeps the DOS window open *after* command has been
' executed. Default behavior is to auto-close. (See
' remarks section for additional information.)
' windowState : Determines the window state of the DOS prompt
' *during* command execution.
' Output : True if completed with no errors, False if error encountered.
' Remarks : If the windowState property is set to vbHide while the keepAlive
' parameter is set to True, then windowState will be changed to
' vbNormalFocus.
'--------------------------------------------------------------------------------
On Error GoTo Err_Hnd
Const lngMatch_c As Long = 0
Const strCMD_c As String = "cmd.exe"
Const strComSpec_c As String = "COMSPEC"
Const strTerminate_c As String = " /c "
Const strKeepAlive_c As String = " /k "
Dim strCmdPath As String
Dim strCmdSwtch As String
If keepAlive Then
If windowState = vbHide Then
windowState = vbNormalFocus
End If
strCmdSwtch = strKeepAlive_c
Else
strCmdSwtch = strTerminate_c
End If
strCmdPath = VBA.Environ$(strComSpec_c)
If VBA.StrComp(VBA.Right$(strCmdPath, 7), strCMD_c, vbTextCompare) <> _
lngMatch_c Then
strCmdSwtch = vbNullString
End If
VBA.Shell strCmdPath & strCmdSwtch & command, windowState
CommandLine = True
VBA.Shell Nothing
Exit Function
Err_Hnd:
CommandLine = False
End Function
Do anyone have this issue?
Using this construct
Option Explicit
Public Sub Find_Files()
Dim fileDetails() As String
fileDetails = Split(CreateObject("wscript.shell").exec("cmd /c forfiles /P C:\Users\User\Desktop\TestFolder /S /D -19/04/2018").StdOut.ReadAll, vbCrLf)
Dim i As Long
For i = LBound(fileDetails) To UBound(fileDetails)
If Not IsEmpty(fileDetails(i)) Then Debug.Print fileDetails(i)
Next i
End Sub
Another question abt same problem - how can i check all files in network drive?
i've tried with
cmd /c pushd "network drive path" forfiles /S /D +14/04/2018
and it doesnt work, however when i write it in console in seperate lines
pushd "network_drive"
forfiles /s /d +10/04/2018
popd
then all works.
Any ideas?
SOLVED:
fileDetails = Split(CreateObject("wscript.shell").exec("cmd /c pushd " & Chr(34) & IMPORT_PATH & FOLDER_PATH & Chr(34) & " & forfiles /S /D +" & s_date & " & popd").StdOut.ReadAll, Chr(10))
And it works for net drive

Can't run DIR from WScript Shell in VBA?

I use the following function in a lot of my VBA projects. I initially added the reference to Windows Script Host Object model to take advantage of Intellisense, but then switched to late binding so I didn't have to reference a bunch of stuff.
Private Function RunCMD(ByVal strCMD As String) As String
'Runs the provided command
Dim oShell As Object 'New WshShell
Dim cmd As Object 'WshExec
Dim x As Integer
Const WshRunning = 0
On Error GoTo wshError
x = 0
RunCMD = "Error"
Set oShell = CreateObject("Wscript.Shell")
Set cmd = oShell.Exec(strCMD)
'Debug.Print strCMD
'Stop
Do While cmd.Status = WshRunning
Sleep 100 'for 1/10th of a second
x = x + 1
If x > 1200 Then 'We've waited 2 minutes so kill it
cmd.Terminate
MsgBox "Error: Timed Out", vbCritical, "Timed Out"
End If
Loop
RunCMD = cmd.StdOut.ReadAll & cmd.StdErr.ReadAll
Set oShell = Nothing
Set cmd = Nothing
Exit Function
wshError:
On Error Resume Next
RunCMD = cmd.StdErr.ReadAll
Resume Next
End Function
It works great when you do something like
RunCMD("ping www.bing.com") or
RunCMD("winrs -r:" & strHost & " reg query hklm\system\currentcontrolset\services\cdrom /v start")
However RunCMD("Dir c:\config* /a:-d /b /d /s") fails, and cmd.StdErr.ReadAll gives an Object Variable or With Block not set error. Even a simple RunCMD("Dir") fails.
Why does DIR make the WScript shell crap out? More importantly, how can I use CMD's DIR function (not VBA's DIR function!) to get a list of files that match a search pattern?
Does it work if you preface your dir command with "cmd /c " and wrap your DOS command in double quotes, like
RunCmd("cmd /c ""DIR""")
or
RunCmd("cmd /c ""Dir c:\config* /a:-d /b /d /s""")

Delete file in variable directory with VBScript

I need use vbscript to delete some browser files.
I have simple batch code like
del /q /s /f "C:\Users\%USERNAME%\AppData\Roaming\Opera Software\Opera Stable\Current Session"
rd /s /q "C:\Users\%USERNAME%\AppData\Roaming\Opera Software\Opera Stable\Current Session"
In vbs
Set obj = CreateObject("Scripting.FileSystemObject")
obj.DeleteFile("C:\Users\%USERNAME%\AppData\Roaming\Opera Software\Opera Stable\Current Session")
Problem is that vbs doesn't recognize variable %USERNAME% and I am getting error "no file in this directory".
Could someone tell me how to write variable directory/path in this language?
From Help.
Returns an environment variable's expanded value.
object.ExpandEnvironmentStrings(strString)
imageArguments
object
WshShell object.
strString
String value indicating the name of the environment variable you want to expand.
Remarks
The ExpandEnvironmentStrings method expands environment variables defined in the PROCESS environment space only. Environment variable names, which must be enclosed between "%" characters, are not case-sensitive.
imageExample
The following code expands the Windows Directory environment variable and displays it:
Visual Basic Script
set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo "WinDir is " & WshShell.ExpandEnvironmentStrings("%WinDir%")
If you want to do it in vbs you use recursion.
On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
ProcessFolder "c:\users\david candy\documents"
Sub ProcessFolder(FolderPath)
Set fldr = fso.GetFolder(FolderPath)
Set Fls = fldr.files
For Each thing in Fls
wscript.echo thing.path
Next
Set fldrs = fldr.subfolders
For Each thing in fldrs
' wscript.echo thing.name
ProcessFolder thing.path
Next
End Sub
You can try :
Set objFSO = CreateObject("Scripting.FileSystemObject")
set WshShell = CreateObject("WScript.Shell")
UserProfile = WshShell.ExpandEnvironmentStrings("%USERPROFILE%")
Wscript.echo UserProfile
Wscript.echo UserProfile &"\AppData\Roaming\Opera Software\Opera Stable\Current Session"
AppData = WshShell.ExpandEnvironmentStrings("%AppData%")
Wscript.echo AppData
Wscript.echo AppData &"\Opera Software\Opera Stable\Current Session"
If objFSO.FolderExists(AppData &"\Opera Software\Opera Stable\Current Session") Then
objFSO.DeleteFolder AppData &"\Opera Software\Opera Stable\Current Session"
End If

VBA wscript.shell .close giving error

I am using the following code (as found here) in Word2010 to find the target path of a shortcut:
Function Getlnkpath(ByVal Lnk As String)
On Error Resume Next
With CreateObject("Wscript.Shell").CreateShortcut(Lnk)
Getlnkpath = .TargetPath
.Close
End With
End Function
Sub GetLinkPath()
MsgBox Getlnkpath("yourshortcutnamehere")
End Sub
When I run the code as shown (modified to use my shortcut name) I get the following error:
Run-time error '438':
Object doesn't support this property or method
and the .Close line is highlighted for debug. When I comment out .Close the script works fine.
Does this cause problems if the shell doesn't close? I've read that .Close isn't necessary for Wscript.Shell but can't confirm that.
There is no Close method to the shortcut object and that is why you are getting the error. This link lists basic operations of WScript.Shell.
If you are intending to dispose the shell object, the best way to do would be
Set objWshShell = WScript.CreateObject("WScript.Shell")
With objWshShell.CreateShortcut(Lnk)
.Save
Getlnkpath = .TargetPath
End With
Set objWshShell = Nothing
Posting this answer for anyone who is still stuck on trying to close the WScript.Shell Object after creating it and not able to find a solution.
My Vb Script :
Dim wsh As Object
Set wsh = CreateObject("WScript.Shell", vbNothing)
wsh.Run "cmd.exe /C pause"
wsh.Run "taskkill /F /IM cmd.exe"

VBA calling vbs file form Program Files, won't call

I currently have the following code to call a vbs file that is in a folder within Program Files. It was originally in a different location (within the same folder) and it would work, but now there is a padlock symbol next to the folder within Program Files, and after changing the location (VBA updated for this as well), it won't call the file. I'm wondering why this is happening.
Sub ChangeThemeBasic()
Dim filespe As String
filespe = "cmd.exe /c C:\Program Files\Theme Changer\ChangeTheme.vbs"
X = Shell(filespe, 1)
End Sub
EDIT:
This works for some reason, I don't know why though:
Sub Test()
Shell "Explorer.exe ""C:\Program Files\Theme Changer\ChangeTheme.vbs""",1
End Sub
From comments
Sub ChangeThemeBasic()
Dim filespe As String
filespe = "cmd.exe /c " & Environ("AppData") & "\Theme Changer\ChangeTheme.vbs"
X = Shell(filespe, 1)
End Sub