我正在制作一个工具,我需要在Excle文件中使用VBA启动一个程序(我想用VB编写代码)。当我关闭该程序时,它应该向VBA脚本返回一个参数。
我刚刚开始使用VBA脚本,并且还没有编写VB程序的任何代码。但我需要知道,在VBA脚本中写什么,这是可能的。
所以它应该像这样工作:
这可能吗?我需要在VBA脚本和Programm中编写什么来返回参数?
我希望你理解我的意思,你可以帮助我
答案 0 :(得分:0)
您可以将VB .exe设置为返回退出代码。只需确保id不为0(表示成功运行)或259(调用进程将认为进程仍在运行)。下面的VBA运行.exe,等待它关闭,然后返回退出代码。
Option Explicit
' Api declarations
Private Declare Function GetExitCodeProcess Lib "Kernel32" (ByVal hProcess As Long, lpExitCode As Long) As Long
Private Declare Function OpenProcess Lib "Kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Private Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As Long) As Long
Public Function RunProgram(ByVal strFilename As String) As Long
'# PURPOSE: Run a program, wait until closed, and return the exit code
Dim TaskID As Long
Dim hProc As Long
Dim lExitCode As Long
Const ACCESS_TYPE = &H400
Const STILL_ACTIVE = &H103
' Open the program
TaskID = Shell(strFilename, 1)
hProc = OpenProcess(ACCESS_TYPE, False, TaskID)
If Err <> 0 Then
Debug.Print "Cannot start " & strFilename, vbCritical, "Error"
Exit Function
End If
' Wait until program is closed
Do
GetExitCodeProcess hProc, lExitCode
DoEvents
Loop While lExitCode = STILL_ACTIVE
' Return the program's exit code
RunProgram = lExitCode
End Function