vb6 - Visual Basic 6 检查正在运行的 Excel 实例

标签 vb6 excel-2010 excel-2007

我想检查在打开我的程序时是否有任何 excel 实例正在运行。使用了以下代码。

Const ERR_APP_NOTRUNNING As Long = 429
On Error Resume Next
Set xlApp = GetObject("Excel.Application")
If Err = ERR_APP_NOTRUNNING Then
Set xlApp = Nothing
Exit Sub
Else:
Set xlApp = Nothing
MsgBox ("Sorry, please restart after closing all Excel files.")
End
End If

此代码在 Office 2007 中运行良好。但它在 Office 2010 中不起作用。有人可以帮助我,以便它可以在迄今为止的所有 office 版本上运行吗?

最佳答案

这是检查正在运行的进程的 Win32 API 方法。将以下代码复制到模块中:

Option Explicit
DefLng A-Z

Private Const TH32CS_SNAPPROCESS As Long = &H2

Private Type PROCESSENTRY32
   dwSize As Long
   cntUsage As Long
   th32ProcessID As Long
   th32DefaultHeapID As Long
   th32ModuleID As Long
   cntThreads As Long
   th32ParentProcessID As Long
   pcPriClassBase As Long
   dwFlags As Long
   szExeFile As String * 260
End Type

Private Declare Function CreateToolhelp32Snapshot Lib "kernel32" (ByVal dwFlags As Long, _
   ByVal th32ProcessID As Long) As Long
Private Declare Function Process32First Lib "kernel32" (ByVal hSnapshot As Long, _
   lppe As PROCESSENTRY32) As Long
Private Declare Function Process32Next Lib "kernel32" (ByVal hSnapshot As Long, _
   lppe As PROCESSENTRY32) As Long

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

Public Function IsProcessRunning(ByVal sProcessEXE As String) As Boolean

   Dim lProcessSnapshot As Long
   Dim udtProcess As PROCESSENTRY32
   Dim bolExists As Boolean
   
   If LenB(sProcessEXE) <> 0 Then
      lProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0&)
      udtProcess.dwSize = LenB(udtProcess)
      
      If lProcessSnapshot > 0 Then
         If Process32First(lProcessSnapshot, udtProcess) <> 0 Then
            Do
               If InStr(1, Trim0(udtProcess.szExeFile), sProcessEXE, vbTextCompare) > 0 Then
                  bolExists = True
                  Exit Do
               End If
            Loop Until Process32Next(lProcessSnapshot, udtProcess) = 0
         End If
         
         'Close snapshot handle
         CloseHandle lProcessSnapshot
      End If
      
      'Return information
      IsProcessRunning = bolExists
   End If
   
End Function

Private Function Trim0(ByVal sText As String) As String
   Trim0 = Trim$(Replace$(sText, Chr$(0), vbNullString))
End Function

这样称呼

Debug.Print IsProcessRunning("excel.exe")

关于vb6 - Visual Basic 6 检查正在运行的 Excel 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73220260/

相关文章:

c++ - 将 BSTR 从 C++ DLL 函数传递到 VB6 应用程序

vb6 - 从 VB6 在 Excel 中格式化

windows - 64 位机器上的 VB6 应用程序

Excel VBA - 在登录共享点并访问文件之前,在共享点中打开工作簿失败

VB6错误传播

excel-formula - 如何使用Excel公式在列中获取唯一值

Excel 组功能 - 插入行

excel - 计算文本字符串中的通配符日期

vba - Tan() 返回错误值

excel - 如何使用 Excel 宏将一段文本从 Word 复制到 Excel?