1

I have VBA code to be run as EXE application when a button is clicked in Excel. My code works well, but it doesn't work when it's minimized. My code is here:

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
altocumulus
  • 21,179
  • 13
  • 61
  • 84

1 Answers1

0

I can solved my question. I used the concept "Close then Re-open". And my solution like code below.

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

I add sub for close my exe before run it again.

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

And these are my reference.
Find running process ID:
VBA Getting program names and task ID of running processes

Kill processes:
VBA script to close every instance of Excel except itself

Community
  • 1
  • 1