Execute command with Excel macro and close cmd window - vba

Here is what I'm trying right now:
Sub del_BJSFM_files()
Call Shell("cmd.exe /S /K" & "cd /d C:\UTAS-SA && del /f/s/q BJSFM > nul", vbNormalFocus)
End Sub
The problem is that the command window stays open.
I tried removing the "/K" but then the command doesn't execute properly.

Here is code for it
Sub del_BJSFM_files()
Call Shell("cmd.exe /S /c" & "cd /d C:\UTAS-SA && del /f/s/q BJSFM > nul", vbNormalFocus)
End Sub
I replaced /k with /c and now it closes the window.

/C - Run Command and then terminate
/K - Run Command and then return to the CMD prompt. This is useful for testing, to examine variables
Source - https://ss64.com/nt/cmd.html

Related

vba: execute shell after finishing previous shell

How to call the second shell in this case after pressing pause?
Shell "cmd /c cd %tmp% && echo hello > tmpfile && pause", 1
Shell "cmd /c cd %tmp% && echo hello > tmpfile && pause", 1
and in this case
Shell "cmd /c cd %tmp% && echo hello > tmpfile", 0
Shell "cmd /c cd %tmp% && echo hello > tmpfile", 0
The Shell command you're using is asynchronous meaning it can run more than one process at a time, so in the case of your two Shell statements in a row, both will be executed simultaneously.
An alternative way is to instead use the Run command of Windows Script Host (WScript.Shell) since it has more options including one to wait for execution of the program to finish before it continues.
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
You can also hide the window completely by specifying False as the second parameter. (Caution with that option if user input is required!)
For example:
Sub demo()
ShellWait "x:\test.bat"
Beep
MsgBox "Finished running!"
End Sub
More Information:
Chip Pearson : Shell and Wait
Stack Overflow : Wait for shell command to complete
Stack Overflow : Wait for Shell to finish, then format cells
DevGuru : WSH » wshshell » Run

Delete all files with extension .c using shell command in vba

i want to delete all files with extension ".c" in a folder from shell command in vba, below code i am not able to execute in VBA Macro. should there be any issue if folder name contains spaces in it or what changes should be done in code
all_C_Files = Selected_User_Output_Folder & "*.C"
Shell "cmd /c del /F" & all_C_Files
'Selected_User_Output_Folder = "C:\Users\Berater\Desktop\Config File Generator"
Why to use shell command at all when you can use Kill
Sub test()
Selected_User_Output_Folder = "C:\Users\Berater\Desktop\Config File Generator\*.c"
On Error Resume Next
Kill Selected_User_Output_Folder
End Sub
Always good practice to quote file/folder paths:
all_C_Files = Selected_User_Output_Folder & "*.C"
Shell "cmd /c del /F """ & all_C_Files & """"

Running batch file from Excel VBA

I have a batch file (Windows command line) that creates a VBS file, runs it, and that in turn re-launches the cmd.exe program in elevated mode so that I can copy a file to the System32 folder.
If I run this batch file manually, all goes according to plan, but if I run it from a VBA Excel macro the batch file gets stuck in an infinite loop, even after the UAC prompt has appeared and I have allowed elevated access. Am I calling the batch file incorrectly from VBA?
I'm fine with VBA, OKish with windows CMD, but haven't often used the two together.
I've tried the following statements in my macro, all 3 have the same result:
Shell Environ("USERPROFILE") & "\Desktop\TEMP.bat"
CreateObject("WScript.Shell").Run "CMD /C %USERPROFILE%\Desktop\TEMP.bat", 0, False
Debug.Print CreateObject("WScript.Shell").Exec("CMD /C %USERPROFILE%\Desktop\TEMP.bat").StdOut.ReadAll
For what it's worth, this is the Batch file code:
#ECHO OFF
:----------------------
>NUL 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
IF '%ERRORLEVEL%' NEQ '0' (
GOTO UACPrompt
) ELSE ( GOTO gotAdmin )
:UACPrompt
ECHO Set UAC = CreateObject^("Shell.Application"^) > "%TEMP%\getadmin.vbs"
ECHO UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%TEMP%\getadmin.vbs"
"%TEMP%\getadmin.vbs"
EXIT /B
:gotAdmin
IF EXIST "%temp%\getadmin.vbs" ( DEL "%TEMP%\getadmin.vbs" )
PUSHD "%CD%"
CD /D "%~dp0"
:----------------------
:: < REST OF SCRIPT HERE - NOT RELEVANT TO QUESTION >
And this is what's in the VBS file:
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "C:\Users\SO\Desktop\TEMP.bat", "", "", "runas", 1
Any pointers/suggestions welcome. Thanks in advance.
I had faced the same problem, and below code solved it. Howerver, the problem is Shell doesn't have bWaitOnReturn option.
Dim Foldername As String
Foldername = "C:\WorkspaceRFT\RMS\command.bat"
Shell "C:\WINDOWS\explorer.exe """ & Foldername & "", vbNormalFocus

Sending multiple commands from Visual Basic to cmd

So I have batch file that contains series of commands. (about 10) -
I've decided that I would like to create simple gui for this tool - simply one button that would execute commands one after another (when command A is finished command B starts)
Thing is that I do not want to use SendKey method, I am looking for a way that would not even show command prompt window. Is there any way to achieve this?
I am obviously beginner, so any help is welcome :).
Thank you very much!
This is part of the batch file that I somehow need to "translate" to VBA code.
wevtutil epl Application %temp%\Sysinfo\AppLog.evtx
wevtutil epl System %temp%\Sysinfo\SystemLog.evtx
takeown /f %temp%\Sysinfo /r /d y
icacls %temp%\Sysinfo /grant administrators:F /T
set FILETOZIP=%temp%\Sysinfo
set TEMPDIR=%temp%\Zip
rd /s /q %TEMPDIR%
mkdir %TEMPDIR%
copy %FILETOZIP% %TEMPDIR%
echo Set objArgs = WScript.Arguments > _zipIt.vbs
echo InputFolder = objArgs(0) >> _zipIt.vbs
echo ZipFile = objArgs(1) >> _zipIt.vbs
echo CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, True).Write "PK" ^& Chr(5) ^& Chr(6) ^& String(18, vbNullChar) >> _zipIt.vbs
echo Set objShell = CreateObject("Shell.Application") >> _zipIt.vbs
echo Set source = objShell.NameSpace(InputFolder).Items >> _zipIt.vbs
echo objShell.NameSpace(ZipFile).CopyHere(source) >> _zipIt.vbs
echo wScript.Sleep 2000 >> _zipIt.vbs
CScript _zipIt.vbs %TEMPDIR% %userprofile%\Desktop\Systeminfo.zip
CreateObject("Wscript.Shell").Run """" & WScript.Arguments(0) & """", 0, False
Above runs anything passed on the command line in a hidden window.
& seperates commands on one line
cmd /c dir&time /t%date /t%type c:\windows\win.ini&echo hello

Execute a command in command prompt using excel VBA

I have a fixed command which i need to pass to command prompt using VBA and then the command should run.
e.g. "perl a.pl c:\temp"
following is the command i am trying to use but it just opens command prompt and doesn't run the command.
Call Shell("cmd.exe -s:" & "perl a.pl c:\temp", vbNormalFocus)
Please check.
The S parameter does not do anything on its own.
/S Modifies the treatment of string after /C or /K (see below)
/C Carries out the command specified by string and then terminates
/K Carries out the command specified by string but remains
Try something like this instead
Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)
You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.
Shell("perl a.pl c:\temp")
-Edit-
To wait for the command to finish you will have to do something like #Nate Hekman shows in his answer here
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn