By executing the below code, you can run any .bat file in Excel Macro. This is very important that you should keep your Excel Sheet from which you want to execute the Batch file in “C:\” drive only. It can be inside any other sub-folder but in C drive Only.
shell("c:\abc.bat")
' OR
shell("CMD.EXE /c c:\abc.bat")
It is a good practise to add two commands in the begin of your bat files,
1)cd c:FolderLocationWithBatFile
2)c:
Doing so the cmd will switch to the drive and location of the bat file,
then the bat file can be found and executed. It works dependless on the current path.
Thanks Olorus for the feedback 🙂
Yes but that is for inside the .bat file. But to launch that batch file, we need to specify the path where exactly that batch file is sitting. That path you can give only in your Shell command.
Let me know, if I am wrong 🙂 🙂
awesome!
I want to create/modify a bat file from the contents of the excel sheet
ex: i want to copy all contents from A5:A25 cells to a bat file and execute the same
is it possible to so..?
I use this to save the PreLogin images from Windows:
Sub GetPreLoginPics()
Dim the_Batch As String
Dim iRow As Integer
Dim PID As Variant
the_Batch = Application.DefaultFilePath & “\GetPreLoginPics.bat”
Open the_Batch For Output As #1
iRow = 5
While Cells(iRow, 1).Value “”
Print #1, Cells(iRow, 1).Value
iRow = iRow + 1
Wend
Close #1
Shell (the_Batch) ‘ runs the batch file
End Sub
‘*******************************************************
The batch commands are in the current worksheet beginning in A5.
@echo off
rem
rem This batch file copies pre-login photos to %userprofile%\desktop\PreLoginPics.
rem See http://bit.ly/3tFMvYq for the Microsoft instructions on this process.
rem
if exist %userprofile%\AppData\Local\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\LocalState\Assets\ (
cd %userprofile%\AppData\Local\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\LocalState\Assets
) else (
exit /b 1
)
if exist %userproifile%\desktop\PreLoginPics\ (
rem The folder has already been created.
) else if exist %userproifile%\desktop\PreLoginPics (
rem There is a FILE named PreLoginPics so we do not continue.
exit /b 2
) else (
rem %userproifile%\desktop\PreLoginPics does not exist
md %userproifile%\desktop\PreLoginPics
)
copy /Y %userprofile%\AppData\Local\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\LocalState\Assets\*.* %userproifile%\desktop\PreLoginPics\*.jpg
start explorer %userproifile%\desktop\PreLoginPics
exit /b 0