在Excel中单击按钮时,我将VBA代码作为EXE应用程序运行。我的代码运行良好,但在最小化时它不起作用。 我的代码在这里:
Sub GoToMenu()
Dim prvDir As String
On Error GoTo CallApp
'Get current directory before change
prvDir = CurDir
'Change to workbook directory
ChDrive ThisWorkbook.Path
ChDir (ThisWorkbook.Path)
'Active program via title
AppActivate ("My exe file title")
'Change back to previous directory
ChDrive prvDir
ChDir prvDir
On Error GoTo 0
Exit Sub
CallApp:
'Run MenuExcel.exe
Shell ThisWorkbook.Path + "\ExcelMenu.exe", vbNormalFocus
'Change back to previous directory
ChDrive prvDir
ChDir prvDir
End Sub
答案 0 :(得分:0)
我可以解决我的问题。我使用了概念"关闭然后重新打开"。我的解决方案就像下面的代码一样。
Sub GoToMenu()
Dim prvDir As String
On Error GoTo CallApp
'Get current directory before change
prvDir = CurDir
'Find "ExcelMenu" process and kill it before reopen
Call CloseExcelMenu
'Change directory to workbook directory
ChDrive ThisWorkbook.Path
ChDir (ThisWorkbook.Path)
CallApp:
On Error GoTo 0
'Run ExcelMenu.exe
Shell ThisWorkbook.Path + "\ExcelMenu.exe", vbNormalFocus
'Change back to previous directory
ChDrive prvDir
ChDir prvDir
End Sub
我再次运行它之前添加sub for close my exe。
Sub CloseExcelMenu()
Dim strComputer As String
Dim objServices As Object, objProcessSet As Object, Process As Object
'Find running Process ID "ExcelMenu.exe"
strComputer = "."
Set objServices = GetObject("winmgmts:\\" _
& strComputer & "\root\CIMV2")
Set objProcessSet = objServices.ExecQuery _
("Select Name, ProcessID FROM Win32_Process", , 48)
'Find the process ID with Process name
For Each Process In objProcessSet
If Process.properties_("Name").Value = "ExcelMenu.exe" Then
'Script for terminate process with image name
Shell "taskkill /PID " & Process.properties_("ProcessID"), vbNormalFocus
End If
Next
Set objProcessSet = Nothing
End Sub
这些是我的参考
查找正在运行的进程ID:
VBA Getting program names and task ID of running processes
杀死进程:
VBA script to close every instance of Excel except itself