Vba excel call shell

Запуск исполняемой программы с помощью функции Shell в VBA Excel. Синтаксис функции Shell, ее параметры, возвращаемые значения, примеры.

Shell – это функция, которая запускает указанную исполняемую программу и возвращает значение Variant (Double), представляющее идентификатор задачи запущенной программы, или возникает ошибка, если функция Shell не может запустить указанную программу.

Синтаксис

Синтаксис функции Shell:

Shell(pathname, [windowstyle])

Если значение функции присваивается переменной, параметры должны быть заключены в скобки. Если функция Shell используется только для запуска программы из кода VBA Excel, параметры должны быть указаны без скобок.

Параметры

Параметры функции Shell:

Параметр Описание
pathname Обязательный параметр. Значение типа Variant (String), задающее имя программы, которую требуется выполнить, и которое может включать диск, каталоги и папки, а также дополнительные параметры при использовании cmd.
windowstyle Необязательный параметр. Значение типа Variant (Integer), задающее стиль окна, в котором будет запущена программа. Если аргумент windowstyle опущен, программа запускается в свернутом окне и получает фокус.

Константы

Константы VBA Excel, задающие стиль окна (windowstyle):

Константа Значение Описание
vbHide 0 Окно скрыто, фокус переходит к скрытому окну.
vbNormalFocus 1 Окно восстанавливает свое исходное положение и размер, а также получает фокус.
vbMinimizedFocus 2 Окно отображается в виде значка, а также получает фокус.
vbMaximizedFocus 3 Окно разворачивается на весь экран, а также получает фокус.
vbNormalNoFocus 4 Окно восстанавливает свое исходное положение и размер, но фокус не получает.
vbMinimizedNoFocus 6 Окно отображается в виде значка, но фокус не получает.

Примечания

  • Если функция Shell успешно запускает указанную программу, возвращается код (идентификатор) задачи запущенной программы (ID процесса в Диспетчере задач). Если функция Shell не может запустить указанную программу из кода VBA Excel, происходит ошибка.
  • Если в полном имени запускаемой программы содержатся пробелы, полное имя программы следует заключить в тройные кавычки (три пары двойных кавычек): """C:Program FilesПапка программыимя.exe""".
  • По умолчанию функция Shell запускает другие программы асинхронно. Это означает, что программа, запущенная с помощью команды Shell, может не завершиться до того, как будут выполнены операторы, следующие за функцией Shell.

Примеры

Пример 1
Запустим с помощью функции Shell программу Notepad++, отобразим идентификатор задачи в информационном окне MsgBox и сравним его с ID процесса в Диспетчере задач.

Используем в параметре pathname тройные кавычки (три пары двойных кавычек), так как полное имя файла содержит пробелы:

Sub Primer1()

Dim myTest

    myTest = Shell(«»«C:Program Files (x86)Notepad++notepad++.exe»«», vbNormalFocus)

MsgBox myTest

End Sub

ID процесса в информационном окне MsgBox:

ID процесса в информационном окне MsgBox

ID процесса в Диспетчере задач:

ID процесса в Диспетчере задач

Пример 2
Запуск проводника Windows из кода VBA Excel с помощью функции Shell.

Обе строки открывают окно проводника Windows с набором дисков и папок по умолчанию:

Shell «C:Windowsexplorer.exe», vbNormalFocus

Shell «explorer», vbNormalFocus

Обе строки открывают папку «Текущая папка»:

Shell «C:Windowsexplorer.exe C:UsersPublicТекущая папка», vbNormalFocus

Shell «explorer C:UsersPublicТекущая папка», vbNormalFocus

Пример 3
Запуск командной строки из кода VBA Excel с помощью функции Shell.

Обе строки запускают программу cmd и открывают окно командной строки:

Shell «C:WindowsSystem32cmd.exe», vbNormalFocus

Shell «cmd», vbNormalFocus

Записываем строку «Большой привет!» в файл «C:Тестовая папкаtest1.txt» (если файл не существует, от будет создан):

Shell «cmd /c echo Большой привет!>»«C:Тестовая папкаtest1.txt»«», vbHide

Здесь полное имя файла является параметром программы cmd, поэтому, если оно содержит пробелы, оно заключается в две пары двойных кавычек, а не в три, как параметр pathname функции Shell.

Константа vbHide используется для того, чтобы при выполнении команды не мелькало окно командной строки.

Параметр «/c» программы cmd указывает, что после выполнения команды программа завершает работу и окно командной строки закрывается. Чтобы программа cmd после выполнения команды продолжила работу и ее окно осталось открытым, вместо параметра «/c» следует указать параметр «/k» и заменить константу vbHide на константу, не скрывающую окно.

Копируем файл «C:Тестовая папкаtest1.txt» в файл «C:Тестовая папкаtest2.txt»:

Shell «cmd /c copy ««C:Тестовая папкаtest1.txt»» ««C:Тестовая папкаtest2.txt»«», vbHide

Смотрите как открывать из кода VBA Excel файлы других приложений и интернет-сайты.


In this Article

  • Call Shell
  • Shell Wait
  • Returning an Error from the Shell Function
  • Open an Existing File With Shell
  • Parameters used by the Shell function
  • Returning a Process ID from the Shell Command
  • Calling Other Programs With  Shell
  • ShellExecute and ShellExecuteEx vs the Shell Command

This tutorial will demonstrate how to use the VBA Shell function.

We can use the VBA Shell function to call a separate, executable program from inside a VBA program. For example, if we need to open Notepad from Excel, we can use the VBA Shell function to do so.  If the Shell call succeeds, it returns the Windows TaskID value of the program it called. If the Shell call fails, it returns zero.

Shell has two input parameters: a required pathname for the program to call, and an optional windowstyle value controlling the style of the window where the program will run. The pathname value can include the program path / directory and arguments.

Call Shell

This code can form part of a macro to run Notepad by using the VBA Call command to call the Shell function.

Call Shell("notepad", vbNormalFocus)

For example:
VBA Shell Notepad

Shell Wait

We can use the VBA Wait command to delay calling the Shell command for a specific period of time.

    Application.Wait (Now + TimeValue("00:00:05"))
    Call Shell("notepad", vbNormalFocus)

Therefore 5 second will pass before the Shell command is called.

Returning an Error from the Shell Function

If we have an error in our code when calling the Shell function, and error will be returned and our code will go into debug mode.

For example, in this macro, we have spelt “note pad” incorrectly.

  Call Shell("note pad", vbNormalFocus)

The result of running this macro will be:
VBA Shell Notepad Error

Open an Existing File With Shell

If we have a specific file that we wish to open with the Shell command, we can include the file name in our code.

Call Shell("Notepad.exe C:demoshell_test.txt", vbNormalFocus)

VBA Shell Notepad OpeningExisting

If we spell the file name incorrectly, the file will not be found and a message box will appear asking us if we wish to create a new file.

VBA Shell Notepad FileNotFound

Parameters used by the Shell function

The Shell function has 2 parameters – the name of the program to call, and the windows style that the program is going to use.  We have been using the vbNormalFocus in the examples above which means that when the program (in this case Notepad) is opened, it has the focus and it opens in the default position and size on the PC.

The Shell offers five other options:

vbHide                                 Hides the window and sets focus on that window

vbMinimizedFocus         Displays the window as an icon with focus

vbMaximizedFocus        Opens the program in a maximized window with focus

vbNormalNoFocus          Restores the window at its most recent position and size

vbMinimizedNoFocus   Displays the window as an icon and the currently active window stays active

Returning a Process ID from the Shell Command

When we run the Shell Command, it returns a Process or Task ID.  We can store the Process ID in a variable, and use that Process ID in running another command – for example, the TaskKill command to close the Notepad file.

Sub TestPID
   Dim ProcessID as integer
   processID = Shell("notepad", vbNormalFocus)
   Call Shell("Taskkill /F /PID " + CStr(processID))
   MsgBox ("Notepad ProcessID = " + CStr(processID))
End Sub

In the first line, NotePad is opened and the Process ID is assigned a value by Windows.  We store this value in the ProcessID variable.  We then use TaskKill to force Notepad to close the instance of NotePad that we have just opened.   The /F switch forces Notepad to end, and the /PID switch tells TaskKill to look for the Notepad Process ID value. The CStr function converts ProcessID to the string format that Shell, and MsgBox on the next line, both need.

VBA Shell Notepad Process ID

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Calling Other Programs With  Shell

Shell will open any other Windows program. For example, this code calls Excel, and opens Excel file ‘example_workbook.xlsx’:

Call Shell("Excel ""C:DEMOexample_workbook.xlsx""", vbNormalFocus)

This shows the opened file:

VBA Shell Excel

ShellExecute and ShellExecuteEx vs the Shell Command

The Windows programming space offers ShellExecute and ShellExecuteEx functions that call external programs from software code. Compared to the VBA Shell function, these Windows functions offer more flexibility, but VBA does not support them and therefore this article does not cover them.

The VBA Shell function runs a command in the operating system shell.

The shell refers to the interface, typically where you type commands, to run programs. This is called a command line interface or CLI.

In Windows, the shell is commonly known as the Command Prompt. To access it, click on the Windows button and type cmd (Windows 10). Windows finds the program for you, so click on it to start it.

search for cmd

In other versions of Windows the process for starting the Command Prompt is similar. Just search for cmd.

Once you are in the command prompt you can type commands like dir to list the folder contents:

using dir

Or you can start programs, like Notepad:

starting notepad

Commands like dir, copy, del etc are known as internal commands because they are built into the shell — they are part of the code that forms the shell, not separate programs.

Programs like Excel, Notepad etc are known as external commands because they are programs in their own right, but can be called or executed from the shell.

The method for calling internal and external programs using the VBA Shell function is different.

You can also use the Shell to run scripts like batch files, PowerShell scripts, PERL, Python etc.

VBA Shell Syntax

The syntax for calling Shell is

Shell (Program,WindowStyle)

Program can be the name of an internal or external command or a script. It can contain any arguments or switches required by the program, as well as the drive and path to the program itself

WindowStyle determines how the window of the called program behaves. WindowStyle is optional but if it is omitted, the program starts minimized with focus. You can specify the WindowStyle using a constant or the actual numeric value, as shown here:

Constant Value Description
vbHide 0 The window is hidden, and focus is passed to the hidden window.
vbNormalFocus 1 The window has focus and appears in its most recent size and position.
vbMinimizedFocus 2 The window is minimized but has focus.
vbMaximizedFocus 3 The window is maximized with focus.
vbNormalNoFocus 4 The window appears in its most recent size and position, and the currently active program retains focus.
vbMinimizedNoFocus 6 The window is minimized, the currently active program retains focus.

Focus is where keyboard input is sent to. If focus is on Excel and you type, the characters appear in Excel. If focus is on Notepad, the characters appear in Notepad.

When you use Shell it returns a Variant (Double) data type that contains the process ID of the program you called. You can use this PID to terminate the program later.

If your attempt to run a program with Shell was unsuccessful, it returns 0.

Examples of Using Shell

External Commands

After we declare a Variant variable called PID, we call Shell to start Notepad like this:

PID = Shell("notepad", vbNormalFocus)

Using vbNormalFocus starts Notepad with its most recent size and position, and changes focus to it.

To close the same instance of Notepad:

PID = Shell ("TaskKill /F /PID " & PID, vbHide)

If you wanted to open Notepad with a specific file then supply the filename, and path if needed:

PID = Shell("notepad c:MyFilesTextFile.txt", vbNormalFocus)

If you are using a shell that doesn’t understand spaces in file names or paths, then you need to wrap the file name/path in two sets of double quotes, inside the double quotes that delimit the Program string:

I’m using Windows 10 and don’t have that issue though.

But if you had wanted to open a file

c:My FilesText File.txt

and your shell required that this be wrapped in «», then you’d write the string like this

PID = Shell("notepad ""c:My FilesText File.txt""", vbNormalFocus)

The same goes for any path you need to specify for the actual command/script name. In this example I’m calling a batch file (Text Parser.bat) to process the text file (Text File.txt):

PID = Shell("""c:My ScriptsText Parser.bat"" ""c:My FilesText File.txt""", vbNormalFocus)

All of those «»» look a bit strange but let me explain. The first and last « mark the beginning and end of the string that specifies the program being called, including any parameters, switches and file(s) it will use:

"""c:My ScriptsText Parser.bat"" ""c:My FilesText File.txt"""

If we remove those « we are left with the Program string itself, which is composed of two separate strings, one for the pathbatch file (red), and the other for the pathfile the batch file will use (blue).

""c:My ScriptsText Parser.bat"" ""c:My FilesText File.txt""

When this is passed to the Shell one of the double « is removed so what is actually seen in the Shell is

"c:My ScriptsText Parser.bat" "c:My FilesText File.txt"

Which looks like two normally delimited strings.

Internal Commands

To call an internal command like dir, you must start an instance of the actual shell, which in Windows is cmd.exe. You then say that you want to use the dir command. The /k switch specifies that cmd should not terminate after dir has finished. You can terminate cmd later.

PID = Shell("cmd /k dir", vbNormalNoFocus)

Asynchronous Execution

Calls to the Shell are executed asynchronously, VBA will make the call and then continue without waiting for whatever program you called to finish whatever job you asked it to do.

This probably isn’t an issue if you are just trying to open a text file in Notepad. But if you are say, trying to list files in a directory and then you want to import the resultant CSV into Excel, you need to make sure that the CSV file is complete before you do that import.

One way to do this would be to make your VBA sleep or pause.

Error handling

Make sure that you use error handling when making Shell calls. Just in case the program or file you want isn’t in the location you expect, or is missing altogether.

Download Sample Workbook

The sample workbook I’ve prepared contains several examples of VBA Shell calls including the use of error handling and terminating programs you have started.

Enter your email address below to download the sample workbook.

By submitting your email address you agree that we can email you our Excel newsletter.

Содержание

  1. Shell function
  2. Syntax
  3. Remarks
  4. Example
  5. See also
  6. Support and feedback
  7. Функция Shell
  8. Синтаксис
  9. Примечания
  10. Пример
  11. См. также
  12. Поддержка и обратная связь
  13. VBA Excel. Функция Shell
  14. Функция Shell
  15. Синтаксис
  16. Параметры
  17. Константы
  18. Примечания
  19. Примеры
  20. VBA Shell
  21. Call Shell
  22. Shell Wait
  23. Returning an Error from the Shell Function
  24. Open an Existing File With Shell
  25. Parameters used by the Shell function
  26. Returning a Process ID from the Shell Command
  27. VBA Coding Made Easy
  28. Calling Other Programs With Shell
  29. ShellExecute and ShellExecuteEx vs the Shell Command
  30. VBA Code Examples Add-in

Shell function

Runs an executable program and returns a Variant (Double) representing the program’s task ID if successful; otherwise, it returns zero.

Syntax

Shell(pathname, [ windowstyle ])

The Shell function syntax has these named arguments:

Part Description
pathname Required; Variant (String). Name of the program to execute and any required arguments or command-line switches; may include directory or folder and drive. On the Macintosh, you can use the MacID function to specify an application’s signature instead of its name. The following example uses the signature for Microsoft Word: Shell MacID(«MSWD»)
windowstyle Optional. Variant (Integer) corresponding to the style of the window in which the program is to be run. If windowstyle is omitted, the program is started minimized with focus. On the Macintosh (System 7.0 or later), windowstyle only determines whether or not the application gets the focus when it is run.

The windowstyle named argument has these values:

Constant Value Description
vbHide 0 Window is hidden and focus is passed to the hidden window. The vbHide constant is not applicable on Macintosh platforms.
vbNormalFocus 1 Window has focus and is restored to its original size and position.
vbMinimizedFocus 2 Window is displayed as an icon with focus.
vbMaximizedFocus 3 Window is maximized with focus.
vbNormalNoFocus 4 Window is restored to its most recent size and position. The currently active window remains active.
vbMinimizedNoFocus 6 Window is displayed as an icon. The currently active window remains active.

If the Shell function successfully executes the named file, it returns the task ID of the started program. The task ID is a unique number that identifies the running program. If the Shell function can’t start the named program, an error occurs.

On the Macintosh, vbNormalFocus, vbMinimizedFocus, and vbMaximizedFocus all place the application in the foreground; vbHide, vbNoFocus, and vbMinimizeFocus all place the application in the background.

By default, the Shell function runs other programs asynchronously. This means that a program started with Shell might not finish executing before the statements following the Shell function are executed. To wait for a program to finish, see Determine when a shelled process ends.

Example

This example uses the Shell function to run an application specified by the user. On the Macintosh, the default drive name is «HD» and portions of the pathname are separated by colons instead of backslashes. Similarly, you would specify Macintosh folders instead of WINDOWS .

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Функция Shell

Запускает исполняемую программу и возвращает значение Variant (Double), представляющее идентификатор задачи программы в случае успешного выполнения и ноль в противном случае.

Синтаксис

Shell(путь, [ тип_окна ])

Синтаксис функции Shell использует следующие именованные аргументы:

Part Описание
путь Обязательный элемент; Variant (String). Имя программы, которую требуется выполнить, и все требуемые аргументы или параметры командной строки; может включать в себя каталог или папку и диск. В macOS можно использовать функцию MacID для указания подписи приложения вместо его имени. В следующем примере используется подпись для Microsoft Word: Shell MacID(«MSWD»)
тип_окна Необязательный элемент. Значение типа Variant (Integer), определяющее тип окна, в котором будет запущена программа. Если аргумент тип_окна опущен, программа запускается в свернутом окне с фокусом на нем. В Mac OS 7.0 и более поздних версиях аргумент тип_окна определяет лишь то, получит ли запускаемое приложение фокус.

Аргумент тип_окна может принимать следующие значения:

Константа Значение Описание
vbHide 0 Окно скрыто, фокус переходит к скрытому окну. Константа vbHide не действует в macOS.
vbNormalFocus 1 Окно получает фокус и восстанавливает свое исходное положение и размер.
vbMinimizedFocus 2 Окно отображается в виде значка и получает фокус.
vbMaximizedFocus 3 Окно разворачивается во весь экран и получает фокус.
vbNormalNoFocus 4 Восстанавливается последнее положение и размер окна. Активное окно остается активным.
vbMinimizedNoFocus 6 Окно отображается в виде значка. Активное окно остается активным.

Примечания

Если функция Shell успешно запускает указанный файл, возвращается код задачи запущенной программы. Код задачи — это уникальный номер, идентифицирующий запускаемую программу. Если функция Shell не может запустить указанную программу, возникает ошибка.

В macOS при указании параметра vbNormalFocus, vbMinimizedFocus или vbMaximizedFocus приложение становится активным. При указании параметров vbHide, vbNoFocus или vbMinimizeFocus приложение запускается в фоновом режиме.

По умолчанию функция Shell запускает другие программы асинхронно. Это значит, что программа, запущенная с помощью команды Shell, может не завершиться до того, как будут выполнены операторы, следующие за функцией Shell. Сведения об ожидании завершения программы см. в статье Определение времени окончания процесса в оболочке.

Пример

В этом примере функция Shell используется для запуска указанного пользователем приложения. В macOS диск по умолчанию обозначается «HD», а части аргумента «путь» отделяются друг от друга двоеточиями вместо обратной косой черты. Аналогичным образом, следует указывать папки macOS вместо WINDOWS .

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA Excel. Функция Shell

Запуск исполняемой программы с помощью функции Shell в VBA Excel. Синтаксис функции Shell, ее параметры, возвращаемые значения, примеры.

Функция Shell

Синтаксис

Синтаксис функции Shell:

Если значение функции присваивается переменной, параметры должны быть заключены в скобки. Если функция Shell используется только для запуска программы из кода VBA Excel, параметры должны быть указаны без скобок.

Параметры

Параметры функции Shell:

Параметр Описание
pathname Обязательный параметр. Значение типа Variant (String), задающее имя программы, которую требуется выполнить, и которое может включать диск, каталоги и папки, а также дополнительные параметры при использовании cmd.
windowstyle Необязательный параметр. Значение типа Variant (Integer), задающее стиль окна, в котором будет запущена программа. Если аргумент windowstyle опущен, программа запускается в свернутом окне и получает фокус.

Константы

Константы VBA Excel, задающие стиль окна (windowstyle):

Константа Значение Описание
vbHide 0 Окно скрыто, фокус переходит к скрытому окну.
vbNormalFocus 1 Окно восстанавливает свое исходное положение и размер, а также получает фокус.
vbMinimizedFocus 2 Окно отображается в виде значка, а также получает фокус.
vbMaximizedFocus 3 Окно разворачивается на весь экран, а также получает фокус.
vbNormalNoFocus 4 Окно восстанавливает свое исходное положение и размер, но фокус не получает.
vbMinimizedNoFocus 6 Окно отображается в виде значка, но фокус не получает.

Примечания

  • Если функция Shell успешно запускает указанную программу, возвращается код (идентификатор) задачи запущенной программы (ID процесса в Диспетчере задач). Если функция Shell не может запустить указанную программу из кода VBA Excel, происходит ошибка.
  • Если в полном имени запускаемой программы содержатся пробелы, полное имя программы следует заключить в тройные кавычки (три пары двойных кавычек): «»»C:Program FilesПапка программыимя.exe»»» .
  • По умолчанию функция Shell запускает другие программы асинхронно. Это означает, что программа, запущенная с помощью команды Shell, может не завершиться до того, как будут выполнены операторы, следующие за функцией Shell.

Примеры

Пример 1
Запустим с помощью функции Shell программу Notepad++, отобразим идентификатор задачи в информационном окне MsgBox и сравним его с ID процесса в Диспетчере задач.

Используем в параметре pathname тройные кавычки (три пары двойных кавычек), так как полное имя файла содержит пробелы:

Источник

VBA Shell

In this Article

This tutorial will demonstrate how to use the VBA Shell function.

We can use the VBA Shell function to call a separate, executable program from inside a VBA program. For example, if we need to open Notepad from Excel, we can use the VBA Shell function to do so. If the Shell call succeeds, it returns the Windows TaskID value of the program it called. If the Shell call fails, it returns zero.

Shell has two input parameters: a required pathname for the program to call, and an optional windowstyle value controlling the style of the window where the program will run. The pathname value can include the program path / directory and arguments.

Call Shell

This code can form part of a macro to run Notepad by using the VBA Call command to call the Shell function.

For example:

Shell Wait

We can use the VBA Wait command to delay calling the Shell command for a specific period of time.

Therefore 5 second will pass before the Shell command is called.

Returning an Error from the Shell Function

If we have an error in our code when calling the Shell function, and error will be returned and our code will go into debug mode.

For example, in this macro, we have spelt “note pad” incorrectly.

The result of running this macro will be:

Open an Existing File With Shell

If we have a specific file that we wish to open with the Shell command, we can include the file name in our code.

If we spell the file name incorrectly, the file will not be found and a message box will appear asking us if we wish to create a new file.

Parameters used by the Shell function

The Shell function has 2 parameters – the name of the program to call, and the windows style that the program is going to use. We have been using the vbNormalFocus in the examples above which means that when the program (in this case Notepad) is opened, it has the focus and it opens in the default position and size on the PC.

The Shell offers five other options:

vbHide Hides the window and sets focus on that window

vbMinimizedFocus Displays the window as an icon with focus

vbMaximizedFocus Opens the program in a maximized window with focus

vbNormalNoFocus Restores the window at its most recent position and size

vbMinimizedNoFocus Displays the window as an icon and the currently active window stays active

Returning a Process ID from the Shell Command

When we run the Shell Command, it returns a Process or Task ID. We can store the Process ID in a variable, and use that Process ID in running another command – for example, the TaskKill command to close the Notepad file.

In the first line, NotePad is opened and the Process ID is assigned a value by Windows. We store this value in the ProcessID variable. We then use TaskKill to force Notepad to close the instance of NotePad that we have just opened. The /F switch forces Notepad to end, and the /PID switch tells TaskKill to look for the Notepad Process ID value. The CStr function converts ProcessID to the string format that Shell, and MsgBox on the next line, both need.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

Calling Other Programs With Shell

Shell will open any other Windows program. For example, this code calls Excel, and opens Excel file ‘example_workbook.xlsx’:

This shows the opened file:

ShellExecute and ShellExecuteEx vs the Shell Command

The Windows programming space offers ShellExecute and ShellExecuteEx functions that call external programs from software code. Compared to the VBA Shell function, these Windows functions offer more flexibility, but VBA does not support them and therefore this article does not cover them.

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

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.

Понравилась статья? Поделить с друзьями:
  • Vba excel byref что это
  • Vba excel borders linestyle
  • Vba excel boolean это что
  • Vba excel autofilter criteria all
  • Vba excel autofill range with