目标
有一个 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/