powered by simpleCommunicator - 2.0.60     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Visual Basic [игнор отключен] [закрыт для гостей] / запуск внешней программы из Excel VBA
5 сообщений из 5, страница 1 из 1
запуск внешней программы из Excel VBA
    #32654922
denis_viktorovich
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Добрый день, не сталкивался ли кто-нибудь с такой задачей:
Нужно из макроса Xls запустить внешний Exe-шник, дождаться пока он проработает и продолжить выполнять макро дальше. проблема в использовании метода с использованием:
prid = Shell("c:\prog.exe", vbHide)
AppActivate prid, 1
заключается в том, что exe в свою очередь не остается активным все время, а так-же открывает документы, выдает окна диалога и т.д.
Пока решил проблему так - prog.exe вывожу на весь экран и делаю его top level, сразу после оператора вызова делаю MsgBox('Предварительная обработка данных завершена!'). Т.е. пока программа не отработает пользователь не видит мессадж и не может его закрыть. Следовательно макрос стоит.
Есть ли другой, более красивый и практичный способ работы с внешними программами из VBA?
Заранее благодарен за советы\замечания.
...
Рейтинг: 0 / 0
запуск внешней программы из Excel VBA
    #32654950
raur
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
c:\prog.exe - ты писал? если да, то можешь дописать ее, чтобы она возвращала что-нить... если нет, то засеки примерное время скоко она у тебя работает и на этот период затормози свою прогу в екселе
...
Рейтинг: 0 / 0
запуск внешней программы из Excel VBA
    #32654951
Фотография big-duke
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
msdn
HOWTO: 32-Bit App Can Determine When a Shelled Process Ends
Last reviewed: August 7, 1998
Article ID: Q129796



--------------------------------------------------------------------------------


The information in this article applies to:
Microsoft Visual Basic for Windows Learning, Professional, and Enterprise Editions, version 6.0
Standard, Professional, and Enterprise Editions of Microsoft Visual Basic, 32-bit only, for Windows, version 4.0


SUMMARY
Executing the Shell() function in a Visual Basic for Windows program starts another executable program asynchronously and returns control to the Visual Basic application. This shelled program continues to run independently of your application until the user closes it.

However, if your Visual Basic application needs to wait for the shelled process to terminate, you could use the Windows API to poll the status of the application, but this is not a very efficient technique. The example in this article demonstrates a better way.

A 16-bit application would use a completely different technique to accomplish the same effect. For additional information on the 16-bit process, please refer the following Knowledge Base article:


ARTICLE-ID: Q96844
TITLE : HOWTO: Determine When a Shelled Process Has Terminated


MORE INFORMATION
The Win32 API has integrated functionality that enables an application to wait until a shelled process has completed. To use these functions, you need a handle to the shelled process. The easiest way to achieve this is to use the CreateProcess() API function to launch your shelled program rather than Visual Basics Shell() function.



Creating the Shelled Process
In a 32-bit application, you need to create an addressable process. To do this, use the CreateProcess() function to start your shelled application. The CreateProcess() function gives your program the process handle of the shelled process via one of its passed parameters.



Waiting for the Shelled Process to Terminate
Having used CreateProcess() to get a process handle, pass that handle to the WaitForSingleObject() function. This causes your Visual Basic application to suspend execution until the shelled process terminates.



Getting the Exit Code from the Shelled Application
It was common for a DOS application to return an exit code indicating the status of the completed application. While Windows provides other ways to convey the same information, some applications only provide exit codes. Passing the process handle to the GetExitCodeProcess() API allows you to retrieve this information.

Below are the steps necessary to build a Visual Basic for Windows program that uses the CreateProcess() function to execute the Windows Notepad (NOTEPAD.EXE) application. This code demonstrates how to use the Windows API CreateProcess() and WaitForSingleObject() functions to wait until a shelled process terminates before resuming execution. It also uses the GetExitCodeProcess() function to retrieve the exit code of the shelled process, if any.

The syntax of the CreateProcess() function is extremely complicated, so in the example code, it is encapsulated into a function called ExecCmd(). ExecCmd() takes one parameter, the command line of the application to execute.



Step-by-Step Example

Start a new project in Visual Basic. Form1 is created by default.

Add the following code to the General Declarations section of Form1:


Private Type STARTUPINFO
cb As Long
lpReserved As String
lpDesktop As String
lpTitle As String
dwX As Long
dwY As Long
dwXSize As Long
dwYSize As Long
dwXCountChars As Long
dwYCountChars As Long
dwFillAttribute As Long
dwFlags As Long
wShowWindow As Integer
cbReserved2 As Integer
lpReserved2 As Long
hStdInput As Long
hStdOutput As Long
hStdError As Long
End Type

Private Type PROCESS_INFORMATION
hProcess As Long
hThread As Long
dwProcessID As Long
dwThreadID As Long
End Type

Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal _
hHandle As Long, ByVal dwMilliseconds As Long) As Long

Private Declare Function CreateProcessA Lib "kernel32" (ByVal _
lpApplicationName As Long, ByVal lpCommandLine As String, ByVal _
lpProcessAttributes As Long, ByVal lpThreadAttributes As Long, _
ByVal bInheritHandles As Long, ByVal dwCreationFlags As Long, _
ByVal lpEnvironment As Long, ByVal lpCurrentDirectory As Long, _
lpStartupInfo As STARTUPINFO, lpProcessInformation As _
PROCESS_INFORMATION) As Long

Private Declare Function CloseHandle Lib "kernel32" _
(ByVal hObject As Long) As Long

Private Declare Function GetExitCodeProcess Lib "kernel32" _
(ByVal hProcess As Long, lpExitCode As Long) As Long

Private Const NORMAL_PRIORITY_CLASS = &H20&
Private Const INFINITE = -1&

Public Function ExecCmd(cmdline$)
Dim proc As PROCESS_INFORMATION
Dim start As STARTUPINFO

' Initialize the STARTUPINFO structure:
start.cb = Len(start)

' Start the shelled application:
ret& = CreateProcessA(0&, cmdline$, 0&, 0&, 1&, _
NORMAL_PRIORITY_CLASS, 0&, 0&, start, proc)

' Wait for the shelled application to finish:
ret& = WaitForSingleObject(proc.hProcess, INFINITE)
Call GetExitCodeProcess(proc.hProcess, ret&)
Call CloseHandle(proc.hProcess)
ExecCmd = ret&
End Function

Sub Form_Click()
Dim retval As Long
retval = ExecCmd("notepad.exe")
MsgBox "Process Finished, Exit Code " & retval
End Sub



Press the F5 key to run the application.

Using the mouse, click the Form1 window. At this point the NotePad application is started.

Terminate NotePad. A MsgBox will appear indicating termination of the NotePad application and an exit code of 0. To test this sample with an application that returns an exit code, implement Knowledge Base article Q178357 and change the parameter passed to ExecCmd to "project1.exe."
NOTE: The MsgBox statement following the ExecCmd() function is not executed because the WaitForSingleObject() function prevents it. The message box does not appear until Notepad is closed when the user chooses Exit from Notepad's File menu (ALT, F, X).


REFERENCES

ARTICLE-ID: Q178357
TITLE : HOWTO: Set an Error Level from a Visual Basic Application





--------------------------------------------------------------------------------
Additional query words: GetModuleUsage kbVBp400 kbVBp600 kbVBp kbdsd
kbDSupport
Platform : WINDOWS
Issue type : kbhowto


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: August 7, 1998
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.
...
Рейтинг: 0 / 0
запуск внешней программы из Excel VBA
    #32655079
Фотография PA
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Можно через WSH:
Код: plaintext
1.
Set WshShell = CreateObject("WScript.Shell")
Return = WshShell.Run("c:\prog.exe",  0 , True)
...
Рейтинг: 0 / 0
запуск внешней программы из Excel VBA
    #32656079
Фотография big-duke
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
2PA - красиво
про wsh все время забываю :)
...
Рейтинг: 0 / 0
5 сообщений из 5, страница 1 из 1
Форумы / Visual Basic [игнор отключен] [закрыт для гостей] / запуск внешней программы из Excel VBA
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]