Bat file in excel

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")

Buy a coffee for the author

Custom Excel Formula to Count based on Color

Custom Excel Formula to Count based on Color

Apr 11, 2023

Dear Readers, Last Friday, my wife, Shagun Sharma, who is a Vlogger shared an excel sheet with some data and a problem to solve, which can save some time of hers. Problem Statement: She had created an Excel sheet for her planning where she used to highlight some of…

A Complete guide to Array in Excel VBA

A Complete guide to Array in Excel VBA

Aug 24, 2022

A complete guide to learning Array in Excel VBA programming. If you have done programming in any language C, VB, Java, Python, etc., you must have definitely heard and known of Array. The array is a data structure that stores data in a sequence. Each of its elements…

Difference between .Text, .Value and .Value2 in Excel VBA

Difference between .Text, .Value and .Value2 in Excel VBA

Aug 10, 2022

One of you raised a question about which property should I be using to get the value of a cell or range — . Text, .Value or .Value2 Most of the time you might have seen all 3 methods being used interchangeably. Rather than answering them in a comment, I thought of…

You May Also Like…

40 Useful Excel Macro [VBA] examples – Part 1 of 2

40 Useful Excel Macro [VBA] examples – Part 1 of 2

Jun 22, 2018

Dear Friends, Here in this article, I have tried to consolidate some most useful and more frequently used excel macro…

read more

Calculate distance between two places in Excel [With Fun]

Calculate distance between two places in Excel [With Fun]

Dec 19, 2016

Dear readers, Last week, I had placed an article on how to create a static google map in excel using Google Static Map…

read more

Excel Tool : Folder Structure Creator

Excel Tool : Folder Structure Creator

Nov 28, 2016

Dear readers, In my previous article I posted an article about how to create folder in windows by Excel VBA code. That…

read more

5 Comments

  1. Olorus

    Olorus
    on February 20, 2012 at 1:53 pm

    • Vishwamitra Mishra

      Vishwamitra Mishra
      on February 20, 2012 at 2:21 pm

  2. Tuisiong

    Tuisiong
    on March 2, 2015 at 4:34 am

  3. Aravind

    Aravind
    on June 30, 2016 at 9:49 pm

  4. Sunseekin

    Sunseekin
    on March 21, 2021 at 1:19 am

This site uses Akismet to reduce spam. Learn how your comment data is processed.

How I can launch a .bat file from excel? For example via an event or a button?

And is it possible to build a .bat file into Excel? For example, I build a launchable .bat file from Excel, a user downloads my Excel file from a server, and then this Excel file can launch the .bat file?

brettdj's user avatar

brettdj

54.6k16 gold badges113 silver badges176 bronze badges

asked Sep 19, 2011 at 12:26

john's user avatar

Running a bat file

To call a .bat file from vba, you can use the shell function:

Sub test()
    Call Shell(Environ$("COMSPEC") & " /c C:Path.bat", vbNormalFocus)
End Sub

Note: the /c closes the DOS prompt when finished.

Creating a .bat file from Excel

You can create a file (a .bat or whatever) with VBA so it could be a txt, a bat or a log file, code is seemingly the same.

Here are some links to begin with:

  • create a log file
  • exporting a text file from Chip Pearson
  • read file

Community's user avatar

answered Sep 19, 2011 at 12:31

JMax's user avatar

JMaxJMax

25.9k12 gold badges69 silver badges88 bronze badges

3

Think of the .xlsx file as a .zip archive. This archive houses the various XML components that build up the Excel file. Note that VBA exposes a special container to work with your custom XML code, through the CustomXMLPart object.

I once stored thumbnails in encoded XML inside an .xlsx file, so storing any text file such as your .bat should be no problem at all.

This MSDN article shows you how to work with CustomXMLPart object from VSTO. Working directly from VBA should be similar.

answered Sep 19, 2011 at 12:34

Gleno's user avatar

GlenoGleno

16.4k11 gold badges62 silver badges85 bronze badges

Joe4

Joe4

MrExcel MVP, Junior Admin


Joe4

Joe4

MrExcel MVP, Junior Admin


  • #4

Here is a good video tutorial that shows you how you can use a Sheell command to rub a bat file.

Note: I am not sure if the bat file you posted is actually what you want to do, or just a simple example of a bat file, because you can easily complete those steps in your example directly in VBA without the having to use a bat file. There are lots of examples you can find about that, if you do a simple Google Search on it. Here are a few:

www.mrexcel.com

Determine if directory exists, if not create it

How do I determine if a directory exists in VBA? How do I create a directory if it does not? I woould like to check the status of a local directory. If it exists, I will move along to the next process. If it does not, I would like to create the directory on the C: drive and then move along…

www.mrexcel.com


www.mrexcel.com

Joe4

Joe4

MrExcel MVP, Junior Admin


  • #6

What I do not know is how to get a bat file to run from a macro button inside an excel xlsm file.

All buttons in Excel have VBA code attached to them — that is what they do, call/run VBA code.
So you really have two options here:
1. Have the VBA code call your batch file (Iike shown in the video linked in my last reply).
2. Have the VBA code remove the directory directly (no need to actually use VBA code do this).

There are tons of posts out there that show you how to remove directories/folders in Excel VBA directly that can be found easily with a Google Search, if you want to go with the second option and avoid using a batch file at all.

Once you have created the VBA code that you are going to use, you would simply then add a button to your worksheet, and assign your VBA code to that button.
Microsoft has a step-by-step tutorial showing you exactly how to do that here:

By the way, I would STRONGLY suggest using the simple «Form Control» button, and not the «ActiveX Control» button.
It is simpler, and has less issues.

Joe4

Joe4

MrExcel MVP, Junior Admin


  • #9

I found a similar post with a similar error

In addition, I did not go to VBA University, therefore for you to suggest «Have the VBA code remove the directory directly (no need to actually use VBA code do this).» is essentially not at all helpful. I would not begin to know what to write for this VBA code.

I do not expect you to write the code yourself. You must have missed this part:

There are tons of posts out there that show you how to remove directories/folders in Excel VBA directly that can be found easily with a Google Search, if you want to go with the second option and avoid using a batch file at all.

Just Google «Excel VBA remove directories», and you will find more examples that you will know what to do with.

If you don’t want to be bothered in doing that and want someone to write the exact code you need, then you will need to explain (in plain English) exactly what you want the code to do.
Just like you did not go to «VBA University», I did not go to «Batch File University». So while I have a general sense of what your batch file does, I am not exactly sure if it is deleting all of directory G or some subset of it.

Last Updated on January 11, 2023 by

CMD Shell in VBA Excel – what it is and how to use it

In this article you will learn how to control other Windows programs from Microsoft Excel using VBA code. If you are trying to do any action in Windows using Excel, the most of these actions are used by the Windows Command Shell, called alse command line . The command line can be run simply by entering the CMD command in the Widnows Start menu. When you enter it, you’ll see the Windows command line window. Command Shell from the VBA Excel level enables:

  • Running any programs from Excel, including running a macro from another Excel file.
  • Controlling Windows tasks
  • Managing files and directories on the disk, copying, deleting, renaming files (when you are using batch file).
  • And every action you can do with the Windows command line, like start formatting your disk 🙂

In this article, we focus on the first three points.

CMD Shell in VBA Excel

Syntax of the Shell function in VBA Excel

How do you most easily use the Command Shell via VBA? Enter the VBA Shell function in the code and give it parameters:

'OfficeInside.Org
Shell(PathName, [WindowStyle As VbAppWinStyle = vbMinimizedFocus]) As Double

PathName – The path of the file that you want to run or the name of the program.

WindowStyle – Optional argument. You can specify in which mode the program will start. Below are all the options that you can use in this param. Whether you enter in the constant argument ie. vbHide, or value = 0, is not important for the operation of the command. They are equivalent. If you don’t complete this argument, the default argument is 1, so vbNormalFocus.

Constant Value Description
vbHide 0 The program runs in the background window. The program window is invisible.
vbNormalFocus 1 The program runs in a visible window in the normal size. The window of the new program is now an active window.
vbMinimizedFocus 2 The program starts in a minimized size window. The window of the new program is now an active window.
vbMaximizedFocus 3 The program starts in the full-size window. The window of the new program is now an active window.
vbNormalNoFocus 4 The program starts in the last used window size and the last used position on the screen. The currently used window remains active.
vbMinimizedNoFocus 6 The program starts in a minimized window. The currently used window remains active.
VBA Excel Shell function – parameters

How to run any program from Excel VBA

Using the VBA Shell function, you can run, most of programs delivered with the Windows system, such as Paint, Notepad, etc. To do this, type the program name in quotes in the first Shell function argument:

Sub vbaShellFunction()
'OfficeInside.Org

      Shell ("notepad") 
      Shell ("mspaint") 
      Shell ("excel")
End Sub

Excel VBA Shell function example

If you want to run a specific file with a specific program, ie. run an Excel file with MsExcel, enter the program name in the Shell function argument, and after the spacebar the file you want to open in it:

 Shell("excel d:Sheet1.xlsx")

To run any file from Excel VBA using the default program set in Windows, type the following in the function argument: explorer.exe.

Shell("explorer.exe d:Sheet1.xlsx")

In this way you opened another Excel file using Excel and VBA.

How to copy, move and delete files and directories from Excel VBA

How to use simple commands to manage data on disk? For example using VBA Excel you can:

  • copy files
  • delete files
  • rename files

All of these activites you can do using VBA Shell function and CMD command. Remember that, after cmd command you need to type this letters: k. All examples are listed here:

Delete file using VB code:

Sub vbaShellDel()

      Shell ("cmd /k delete FILE_PATHFILE_NAME.FILE_EXTENSION")
End Sub

Copy file using VB code:

Sub vbaShellCopy()

      'copy file 
      Shell("cmd /k copy C:FILE_PATHFILE_NAME.FILE_EXTENSION C:NEW_FILE_PATH") 

      'copy whole directory 
      Shell("cmd /k copy C:FILE_PATH* C:NEW_FILE_PATH")
End Sub

Rename file using VB code:

Sub vbaShellRename()

      Shell ("cmd /k RENAME C:FILE_PATHFILE_NAME.FILE_EXTENSION FILE_NAME.FILE_EXTENSION")
End Sub

How to run batch file from Excel VBA?

How to do it? To use the above-mentioned commands, you should create files with the extension bat, called batch files. The bat file in its content should have the shell command ie. copy, delete or rename files. If on the other hand you would like to add parameters for commands, this is not possible from the Shell function level. Other functions of the VBA language are used for this.

How to turn off the computer in VBA Excel

To close programs and turn off the computer from MS Excel, you should create batch files with the extension bat. Below you can find code for these files:

  • Computer shutdown: shutdown/s
  • Computer restart: shutdown/r
  • Computer hibernation: shutdown/h

Here is an example:

Sub vbaShellComputerHiber()

      Shell ("cmd /k shutdown/h")
End Sub

You can download all examples here:

This article is part of the Excel vba course. The course can be found here: VBA course.

@Robert: Я попытался адаптировать ваш код с относительным путем и создал пакетный файл для запуска VBS.

VBS запускается и закрывается, но не запускает макрос… Любая идея о том, где проблема может быть?

Option Explicit

On Error Resume Next

ExcelMacroExample

Sub ExcelMacroExample() 

  Dim xlApp 
  Dim xlBook 

  Set xlApp = CreateObject("Excel.Application")
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  strFilePath = objFSO.GetAbsolutePathName(".") 
  Set xlBook = xlApp.Workbooks.Open(strFilePath, "ExcelsCLIENTES.xlsb") , 0, True) 
  xlApp.Run "open_form"


  Set xlBook = Nothing 
  Set xlApp = Nothing 

End Sub

Я удалил «Application.Quit», потому что мой макрос вызывает пользовательскую форму, заботясь об этом.

Приветствия

ИЗМЕНИТЬ

Я действительно отработал это, на всякий случай, когда кто-то хочет запустить пользовательскую форму «подобно» автономному приложению:

Проблемы, с которыми я столкнулся:

1 — Я не хотел использовать событие Workbook_Open, поскольку excel заблокирован только для чтения.
2 — Команда партии ограничена тем фактом, что (насколько мне известно) она не может вызвать макрос.

Сначала я написал макрос, чтобы запустить мою пользовательскую форму, скрывая приложение:

Sub open_form()
 Application.Visible = False
 frmAddClient.Show vbModeless
End Sub

Затем я создал vbs для запуска этого макроса (выполнение этого с относительным путем было сложным):

dim fso
dim curDir
dim WinScriptHost
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing

Set xlObj = CreateObject("Excel.application")
xlObj.Workbooks.Open curDir & "ExcelsCLIENTES.xlsb"
xlObj.Run "open_form"

И я, наконец, сделал пакетный файл для выполнения VBS…

@echo off
pushd %~dp0
cscript Add_Client.vbs

Обратите внимание, что в моем Userform_QueryClose:

я также включил «Установить обратно в видимый»

Private Sub cmdClose_Click()
Unload Me
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    ThisWorkbook.Close SaveChanges:=True
    Application.Visible = True
    Application.Quit
End Sub

В любом случае, спасибо за вашу помощь, и я надеюсь, что это поможет, если кому-то это понадобится

Like this post? Please share to your friends:
  • Bassotronics one word bass
  • Basic word test microsoft
  • Basic word order in english sentence
  • Basic word order examples
  • Basic word of english language