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 & """"
Related
I am having some problems running a shell command and checking the output of the data. I wish to check using vba if the current remote user of the DB is Active. In
command prompt =
for /f "tokens=1-8" %a in ('quser') do #if "%d"== "Active" echo %COMPUTERNAME% %a %d
returns the users logged on and their state I wish to check that none of them are disconnected ("Disc"). I used this function to check the shell and return the pipe value as a string in a message box
Public Function ShellRun(sCmd As String) As String
'Run a shell command, returning the output as a string'
Dim oShell As Object
Set oShell = CreateObject("WScript.Shell")
'run command'
Dim oExec As Object
Dim oOutput As Object
Set oExec = oShell.Exec(sCmd)
Set oOutput = oExec.StdOut
Debug.Print sCmd
'handle the results as they are written to and read from the StdOut object'
Dim s As String
Dim sLine As String
While Not oOutput.AtEndOfStream
sLine = oOutput.ReadLine
If sLine <> "" Then s = s & sLine & vbCrLf
Wend
ShellRun = s
'example MsgBox ShellRun("cmd.exe /c" & "dir c:\")
End Function
Call Command used on click event
Dim CMDLineCommand As String
CMDLineCommand = "for /f ""tokens=1-8"" %a in ('quser') do #if ""%d""== ""Active"" echo %COMPUTERNAME% %a %d"
'(CMDLineCommand = "dir c:\")<------ THIS WORKS FINE
MsgBox ShellRun("cmd.exe /c " & CMDLineCommand)
This works fine for loads of command line commands I have tested it with but not query and therefore query user. The query user command works fine from command line but does not return anything when issued through a VBA Shell commands.
Any thoughts would be appreciated.
because shell does not know the path of the query.exe(quesr) it does not continue where as command prompt can use system variables to find exe's. solution find the query.exe and copy it to a working directory then run the shell command. mine was located in a hashed folder within C:\Windows\WinSxS be careful as here are 64bit versions and 32 bit.
I'm using below macro in goal of obtaining list of all files in folder :
Sub SO()
Const parentFolder As String = "C:\Users\bloggsj\folder\" '// change as required, keep trailing slash
Dim results As String
results = CreateObject("WScript.Shell").Exec("CMD /C DIR """ & parentFolder & "*.*"" /S /B /A:-D").StdOut.ReadAll
Debug.Print results
Ens Sub
but it gives me invalid output as it doesn't chandle Unicode characters, which are part of files names in my directory. In normal batch file I could use additional command 'CHCP 1250' to change coding page for symbols. But I can't incorpotrate it into above macro. I've tried in several ways like :
results = CreateObject("WScript.Shell").Exec("CMD /C CHCP 1250 DIR """ & parentFolder & "*.*"" /S /B /A:-D").StdOut.ReadAll
and
results = CreateObject("WScript.Shell").Exec("CMD /C ""CHCP 1250"" ""DIR """ & parentFolder & "*.*"" /S /B /A:-D""").StdOut.ReadAll
Ampersand
command1 & command2 : Use to separate multiple commands on one command
line. Cmd.exe runs the first command, and then the second command.
CMD /C CHCP 1250 & DIR ....
However VBA has native support for a directory listing and VBScript can use the FileSystemObject to achieve the same.
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
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
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