Shell from excel vba

Запуск исполняемой программы с помощью функции 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 файлы других приложений и интернет-сайты.


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.

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.

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.

Содержание

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

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.

Источник

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 и обратная связь.

Источник

How can I run a bash file using VBA on MAC OSX

I tried the following code

location = FolderPath(ThisWorkBook.FullName) 

which returns the current directory minus the file name.

followed by

Shell(location &"runmybatch.sh")

I did this because the bash script is located within the same folder as the excel spreadsheet.

Martijn Pieters's user avatar

asked Jun 14, 2012 at 22:57

Mohamed's user avatar

7

There are a couple of surprises that make this tricky!

  1. The Shell function expects paths to be separated by :, not /
  2. When the script runs, it will have the root (/) directory as its working directory

Other than that you should be able to run a bash script using the Shell command. Here are step-by-step instructions to get you started.

  • Create the following bash script in your Desktop directory and name it test.sh:
#!/bin/bash
open /Applications/Calculator.app/
  • Make sure test.sh is executable (from a Terminal window, chmod +x test.sh)
  • Try running it (type ./test.sh in Terminal). The calculator app should appear. Exit that.
  • Run Excel and create a new workbook, Workbook1.
  • Save this blank workbook in the Desktop directory as a Macro-enabled workbook
  • Run VB: Tools > Macro > Visual Basic Editor
  • If the immediate window is not showing, View > Immediate Window
  • In the immediate window, type the following VBA code:
 Shell ActiveWorkbook.Path & ":test.sh"
  • The calculator app should run.

answered Jun 26, 2012 at 23:46

Joel Spolsky's user avatar

Joel SpolskyJoel Spolsky

33.2k17 gold badges88 silver badges104 bronze badges

I had no luck with the shell command, but here’s what worked for me through applescript in Excel 2011:

script_s = "do shell script ""/Users/user/path/to/script/rubyscript_09.rb"""
MacScript script_s

I found it necessary to have the script use a shebang of ‘#!/usr/bin/env ruby‘ (after the install of ruby version manager)

To address a file that is in a subfolder of the folder of the calling file, use this:

FilePathName_s = ThisWorkbook.Path & ":subfolder:filename"

This returns a path with :‘s, which I believe must be converted to /‘s for the do shell script. This can be done with the AppleScript, quoted form of POSIX path of FilePathName_s, or with the VBA FilePathName_s = "/" & Replace(FilePathName_s, ":", "/")

answered Sep 7, 2012 at 0:01

Steph's user avatar

StephSteph

811 gold badge1 silver badge6 bronze badges

At first, Joel’s excellent tutorial didn’t work for me (on OS X 10.11.6 and Excel for Mac 2011). After some sleuthing, I discovered that my problem was caused by «extended attributes» in my script file, test.sh. In Terminal, ls -l test.sh yields:

  -rwxr-xr-x@ 1 tgk  staff  456 Mar 16 13:12 test.sh

Note that «@» indicates the presence of extended file attributes. More information is given by invoking ls -l@ test.sh, which yields:

-rwxr-xr-x@ 1 tgk  staff  456 Mar 16 13:12 test.sh
      com.apple.FinderInfo   32 
      com.apple.TextEncoding     15

In other words, depending on how the file was created, it may or may not have extended attributes. So I stripped off the extended attributes via xattr -c test.sh, and then Joel’s call: Shell ActiveWorkbook.Path & ":test.sh" worked perfectly! Many thanks to all.

____

I later learned that saving the shell script without writing extended attributes is possible in TextWrangler by first invoking defaults write com.barebones.textwrangler WriteExtendedAttributes never in Terminal. However, this only prevents the addition of the com.apple.FinderInfo attribute; the com.apple.TextEncoding attribute remains. Fortunately, however, Joel’s VBA Script command now works when the shell script has just the com.apple.TextEncoding extended attribute! So, TextWrangler is the editor for me!

answered Mar 17, 2017 at 1:06

Tom Kreutz's user avatar

I did not use the FolderPath command, its seems not to be availble to me so I will investigate later why not. Below is some sample code that I have tested to make sure that it is possible to run a .sh file from OSX Excel.

The .sh file I used to test was placed on my desktop and only contains the following line: «open /Applications/Calculator.app»

The VBA code to invoke the .sh from Excel on OSX is below:

Dim DesktopFolder As String
DesktopFolder = MacScript("return (path to desktop folder) as string")

Dim ScriptFile As String
ScriptFile = DesktopFolder & "test.sh"

RetVal = Shell(ScriptFile, vbNormalFocus)

I decided to check if its only functional on certain folders so I moved the .sh file to the /tmp folder and could not execute the file, simply got «file not found errors» no matter how I encoded the path. Finally realised that the /tmp file on OSX is a symbolic link that maps to /private/tmp and when I used that path it all seems to work fine again.

Dim ScriptFile As String
ScriptFile = "Macintosh HD:private:tmp:test.sh"
RetVal = Shell(ScriptFile, vbNormalFocus)

Anyway, hope it helps a bit. I will continue looking for a better way, need something to dynamically find what the file location is reliably.

answered Jun 23, 2012 at 14:16

Joe's user avatar

JoeJoe

6113 silver badges2 bronze badges

I also had trouble getting my simple bash script to work, even though I had it on the global path (/usr/bin) and all users had read and execute permissions. Two things caused my script to fail: permissions and paths due to differences between the AppleScript environment and my user’s bash environment. I found the discussion over at VBA Shell function in Office 2011 for Mac more helpful in solving my problem. Here is the process I eventually settled on.

Because Excel was masking the underlying details, I recommend using the AppleScript Editor, which hopefully gives better insight during your troubleshooting than the meaningless Excel errors I saw:

  1. Use AppleScript Editor to confirm that the script actually works as whatever user and with whatever environment variable happens to be used:

    1. In Spotlight, start typing «applescript editor» until it shows up and then click on it
    2. Create a new AppleScript Editor file
    3. Type your simple script into the new file without doubling the double quotes — mine reads

      do shell script "parseCsvAndOpen.sh"
      
    4. Hit the «Run» button for your script
    5. Track down any issues, make changes, and repeat hitting the «Run» button until you get it to execute from within AppleScript Editor
      • The good news here is that you have a narrower search if you need to go back to StackOverflow or Google for help ;-)
  2. now copy your simple script from AppleScript Editor to your vba and confirm it still works

    1. I was able to just double my double quotes and put it in double quotes after the MacScript code:

      MacScript "do shell script ""parseCsvAndOpen.sh"""
      

      That is indeed one, two, and then three double-quote characters! (presumably escaping the double quotes)

Community's user avatar

answered Jan 3, 2014 at 22:50

sage's user avatar

sagesage

4,7182 gold badges42 silver badges47 bronze badges

I don’t have MS Office for Mac installed, so I can’t test the answer I propose. I suppose it should be possible to call Bash the binary (i.e. /bin/bash) and pass the name of the script you want to execute as an argument. This would avoid any issues with permission bits, and would ensure that the path name for the second argument is the usual Unix-style /-separated one. For the first argument, it might be enough to call bash by its name, without any path, as that should use the PATH environment variable.

All in all, and still without testing, I’d try this:

Shell("bash runmybatch.sh")

Or, if that doesn’t work due to incorrect working directory,

Shell("bash '" & location & "/runmybatch.sh'")

where location is the /-separated path to the directory of the workbook. The sngle quotes should take care of any spaces or other exotic characters in the path.

answered Jun 24, 2012 at 14:42

MvG's user avatar

MvGMvG

56.5k21 gold badges143 silver badges274 bronze badges

What you need to do is write the following command in your VBA macro:

Shell "C:Pathtoscriptlocationscript.sh"

(Remember to include double quotes surrounding the path)

The best way to get your script location is to record a macro to save a workbook in the same folder where your bash script resides. That way you can later see how Excel calls that path and copy/paste it to the shell command above.

Akshay's user avatar

Akshay

8146 silver badges19 bronze badges

answered Sep 3, 2014 at 23:46

Christian's user avatar

0

An introduction to the shell

A shell is an interface in the Windows that runs commands and helps you use programs. Hence it is also called the “Command Line Interface” (CLI). In Windows, we also call it the command prompt.

You can also open the command prompt by typing “cmd” in the Run dialog after clicking on the Windows button on your keyboard.

In Windows 10, we can directly type it intp the search box next to the windows button.

Calling the command prompt from the Windows start menu

Some sample commands

Below are some commands and output that may interest you. If you’re already quite familiar with the shell commands that you have at your disposal, feel free to skip to the next section to learn how to call the shell from VBA.

Internal commands

The above commands are already a part of the shell, so they are called internal commands.

Dir

This command lists the contents of a folder.

Screenshot of dir listing a directory

Ipconfig

This command provides network information.

Systeminfo

Provides all information related to the hardware of the system.

Ping

This command helps to check a the server is reachable.

Tasklist

This command lists out all the tasks in the system that are currently running.

External Commands

There are several programs in the Windows system which may or may not come with the operating system. For example, Notepad, MS Word, MS Excel and any other software that we explicitly install after setting up the operating system.

All these can be invoked using external commands.

notepad

mspaint

Changing the directory and opening a specific document from that directory

Run other scripts using Shell

Below are some of the other scripting languages that can be run using the Windows shell or command prompt.

  1. Powershell
  2. Batch files with the extension “.bat”
  3. PERL
  4. Python
  5. Javascript

And so on…

The VBA Shell function

VBA offers a built-in function named “Shell” to use the Windows shell and run or execute any program with ease.

Syntax

Pid=Shell ( <Program name>, [ <Window Style> ] )

Where

  1. Program name is the name of any internal or external command or a script.
  2. Window Style describes the behavior of the subsequent display window. It is an optional argument and can be any one of values in the table below (which are constants).
  3. Pid is the variable that holds the Process id of the program that is initiated by the shell function. This is a value of double data type that is returned by the Shell function. It can be used later to terminate the program.

Note: If the execution of the function is not successful i.e. if not program is initiated, a 0 value is returned and it gets stored in the Pid variable.

Constant Value Description
vbHide 0 The window is opened and hidden . The focus is passed on to the hidden window.
vbNormalFocus 1 The window opens in its most recent position and size. The widow is visible and gains focus
vbMinimizedFocus 2 The window opens but remains minimized, but it has focus.
vbMaximizedFocus 3 The window is maximized with focus.
vbNormalNoFocus 4 The window opens in its most recent position and size. The widow is visible but does not gains focus. Only the currently active program retains its focus.
vbMinimizedNoFocus 6 The window opens and remains minimized. The program that is currently in focus retains focus.

Wherever we send keyboard input, the focus remains there and whatever keys are pressed or sent, gets typed in the window with focus. For example, if Notepad is in focus, whatever is typed using the keyboard or sendkeys, gets typed in that Notepad window.

Examples

1. Opening a Notepad window using normal focus and closes it using its program ID.

Sub shell_demo()

'declare a variable to hold the process id that is returned
Dim Pr_id As Double

'Use shell function to open a notepad using normal focus
Pr_id = Shell("notepad", vbNormalFocus)

'Kill or close the notepad using the same process id that was returned.
Pr_id = Shell("TaskKill /F /PID " &amp;amp;amp; Pr_id, vbHide)

End Sub

2. The code below opens a Notepad file which already contains some data. So the file path should also be supplied in the parameters. The Notepad application opens with the focus maximized, as specified.

Sub shell_demo2()

'declare a variable to hold the process id that is returned
Dim Pr_id As Double

'Use shell function to open a notepad using maximized focus
Pr_id = Shell("notepad C:UsersLAKSHMI RAMAKRISHNANOneDriveDocumentssai invite.txt", vbMaximizedFocus)

'Kill or close the notepad using the same process id that was returned.
Pr_id = Shell("TaskKill /F /PID " &amp;amp;amp; Pr_id, vbHide)

End Sub

In some cases, Windows does not understand spaces between the file names or file paths. In this event, we need to use double double quotes for the <Program name> parameter.

Pr_id = Shell("notepad ""C:UsersLAKSHMI RAMAKRISHNANOneDriveDocumentssai invite.txt""", vbMaximizedFocus)

This is typically not an issue with Windows 10.

3. Calling programs with different extensions

Sub shell_demo3()

'declare the required variables to hold the process ids that are returned
Dim Pr_id_not, Pr_id_word, Pr_id_acc, Pr_id1, Pr_id2 As Double

'Open a simple notepad using Shell function
Pr_id_not = Shell("Notepad", vbMaximizedFocus)

'Open a simple notepad using Shell function
Pr_id_word = Shell("winword", vbMaximizedFocus)

'Open a simple notepad using Shell function
Pr_id_acc = Shell("MsAccess", vbMaximizedFocus)

'Use shell function to open a folder using maximized focus
Pr_id1 = Shell("Explorer.exe C:UsersLAKSHMI RAMAKRISHNANOneDriveDocumentsTraining", vbMaximizedFocus)

'Use shell function to open a non- Excel file using normal focus
Pr_id2 = Shell("Explorer.exe C:UsersLAKSHMI RAMAKRISHNANOneDriveDocuments5.png", vbNormalFocus)

Debug.Print Pr_id_not
Debug.Print Pr_id_word
Debug.Print Pr_id_acc
Debug.Print Pr_id1
Debug.Print Pr_id2

End Sub	

4. Calling a batch file to run a text file using the Shell function.

Sub shell_demo3()

'declare a variable to hold the process id that is returned
Dim Pr_id_new As Double

'Use shell function to open a notepad using normal focus
Pr_id_new = Shell("""C:Lakshmiprocessme.bat"" ""C:Lakshmitextfile_run.bat""", vbMaximizedFocus)

'Kill or close the notepad using the same process id that was returned.
Pr_id_new = Shell("TaskKill /F /PID " &amp;amp;amp; Pr_id_new, vbHide)

End Sub

Yes, that’s a lot of quotes in the Shell function’s <Program Name> parameter. Let me explain.

  • One double quote each at the two ends “, mark the beginning and end of the string that refers to the name or path of the program to be run.

(“”C:Lakshmiprocessme.bat”” “”C:Lakshmitextfile_run.bat””)

  • The rest of the parameter (with one double quote in front and one at the end) consists of 2 strings. One is the path of the batch file to be run and the other is the path of the text file to be run. As you might know, a double quote needs to be used twice consecutively within a string to have one double quote there (to escape a quote).

(““”C:Lakshmiprocessme.bat“” “”C:Lakshmitextfile_run.bat“”“)

The final string that is passed in the shell is:

“C:Lakshmiprocessme.bat” “C:Lakshmitextfile_run.bat”

Asynchronous Execution

VBA code keeps executing without waiting to see if execution of the command is complete. So if we need to check for the completion of a command’s run before the next command executes, we need to use the VBA sleep or pause statements.

For example, to type something into a Notepad document, we can just open and type using the Shell function. But if we need to list out the files in a directory, we definitely need to verify that the run is complete, then export the list to Excel or CSV afterwards. In this case, we can use a sleep or wait statement to ensure the command is executed fully.

Here is a sample program that explains how to wait.

Sub shell_demo_4()

'Declaration of objects and variables
Dim sh_obj As Object
Dim counter As Integer

'Assign all values
Set ie_pr_id = Nothing
counter = 0
Set sh_obj = CreateObject("shell.application")
counter = sh_obj.Windows.Count
ie = Shell("C:Program FilesInternet Exploreriexplore.exe -nosessionmerging , -noframemerging", vbNormalFocus)

'wait till the window opens
Do Until sh_obj.Windows.Count = counter + 1
Loop

'set the new process id
Set ie_pr_id = sh_obj.Windows(sh_obj.Windows.Count - 1)

'Print the new process id
Debug.Print ie_pr_id

End Sub

Output of the program in the immediate window:

Internet Explorer

Conclusion

The built-in VBA Shell function to execute commands just like how you’d execute commands from the Windows command prompt. You can use it to open any kind of window during the execution of VBA macros, such as automation, web scraping, or file comparison.

Like this post? Please share to your friends:
  • Sheets это vba excel
  • Sheets do not show in excel
  • Sheets в excel что это примеры
  • Sheets count excel vba
  • Sheets vba excel примеры