确定应用程序是否正在使用Excel运行

Ale*_*lex 7 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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

只有当我将"Word.Application"作为可执行文件时,此代码才有效.如果我尝试放"MyProgram.Application",该函数将永远不会看到程序正在运行.如何才能找到"MyProgram.exe"当前打开?

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

end*_*and 13

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

这将根据进程名称进行搜索,并根据需要返回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 & "'")

    If objList.Count > 0 Then
        IsProcessRunning = True
    Else
        IsProcessRunning = False
    End If

End Function
Run Code Online (Sandbox Code Playgroud)