excel - 确定应用程序是否正在与 Excel 一起运行

标签 excel vba

目标

有一个 Excel 文件,其中包含可打开自定义程序的“搜索”按钮。该程序用于研究。如果用户单击按钮时该程序已打开,请将其弹出并聚焦于该给定程序。

现状

这是我尝试使用的代码:

搜索按钮

Private Sub btnSearch_Click()
    Dim x As Variant
    Dim Path As String

    If Not IsAppRunning("Word.Application") Then
        Path = "C:\Tmp\MyProgram.exe"
        x = Shell(Path, vbNormalFocus)
    End If
End Sub

IsAppRunning()

Function IsAppRunning(ByVal sAppName) As Boolean
    Dim oApp As Object
    On Error Resume Next
    Set oApp = GetObject(, sAppName)
    If Not oApp Is Nothing Then
        Set oApp = Nothing
        IsAppRunning = True
    End If
End Function

只有当我将“Word.Application”作为可执行文件时,此代码才会起作用。如果我尝试输入“MyProgram.Application”,该函数将永远不会看到该程序正在运行。如何找到“MyProgram.exe”当前已打开?

此外,我需要把重点放在它上面......

最佳答案

您可以通过获取打开的进程列表来更直接地检查这一点。

这将根据进程名称进行搜索,并根据需要返回 true/false。

Sub exampleIsProcessRunning()  
    Debug.Print IsProcessRunning("MyProgram.EXE")
    Debug.Print IsProcessRunning("NOT RUNNING.EXE")
   
End Sub

Function IsProcessRunning(process As String)
    Dim objList As Object
    
    Set objList = GetObject("winmgmts:") _
        .ExecQuery("select * from win32_process where name='" & process & "'")
    
    IsProcessRunning = objList.Count > 0
End Function

关于excel - 确定应用程序是否正在与 Excel 一起运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29807691/

相关文章:

vba - 使用 VBA 在表中的特定值上方插入一行

python - 如何使用 DataNitro 和 python 保存 excel 文件

excel - 保护 Excel VBA 代码的最佳方法?

excel - VBA - 测试一个值是否是 PivotField 的有效选择

wcf - 如何从 Excel 2003 VBA 调用 WCF 客户端?

excel - 将文件另存为 CSV UTF8 会出现错误 1004

excel - 使用 Excel 2007(Vista 64 位版本)加载 32 位 DLL

excel - 如何每第n行插入函数的值

excel - 如何复制范围内的两个不相邻的列

excel - vba复制不连续范围单元格