Shell 函数返回在第一个参数中指定的应用程序的任务标识号。可使用这个数字在稍后激活该任务。
Shell 函数的第二个参数确定如何显示应用程序(1是正常大小的窗口代码,并带有焦点)。参见“帮助”系统可了解该参数的其他值。
如果Shell 函数没有成功,那么会产生错误。因此,在过程需要一个On Emor语句,如果未发现可执行文件或发生其他错误,则会显示一条消息。
Shell 函数启动的应用程序正在运行时,VBA代码不会中止,理解这一点非常重要。换言之,Shell函异步运行应用程序。如果执行Shell 函数后,过程还有其他指令,它们会与新加载的程序同时执行。如果指令要求用户交互(如显示一个消息框),那么Excel的标题栏会在其他应用程序活动时闪烁。
某些情况下,可能需要用Shell 函数启动一个应用程序,但需要在应用程序关闭之前暂停VBA代码的运行。例如,启动的应用程序可能生成一个文件,用于稍后的代码。虽然不能中止代码的执行,但可创建一个循环,专门用来监视应用程序的状态。下例在Shell 函数启动的应用程序结束时显示一个消息框:
Declare PtrSafe Function OpenProcess Lib "kerne132"(ByVal dwDesiredAccess As Long, _ByVal bInheritHandle As Long, _ByVal dwProcessId As Long) As Long
Declare PtrSafe Function GetExitCodeProcess Lib "kerne132"(ByVal hProcess As Long,1pExitCode As Long) As Long
Sub StartCalc2 ()
Dim TaskID As Long
Dim hProc As Long
Dim IExitCode As Long
Dim ACCESS_TYPE As Integer, STILL_ACTIVE As Integer
Dim Program As String
ACCESS_TYPE=6H400
STILL_ACTIVE-6H103
Program-"Call.exe"
On Error Resume Next
TaskID- Shell (Program, 1)
hProc-OpenProcess (ACCESS_TYPE, False, TaskID)
If Err <>0 Then
MagBox"Cannot start "& Program, vbCritical, "Error"
Exit Sub
End If
Do 'Loop continuously
GetExitCodeProcess hProc, 1ExitCode
DoEvents
Loop While 1ExitCode=STILL_ACTIVE
MsgBox Program &"was closed"
End Sub