Declare Function GetForegroundWindow Lib "user32" () As Long
Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Public ActiveCheck As Boolean
Public TimerActive As Boolean
Public Sub RunOnActivate()
' Your macro code goes here
MsgBox "Welcome back to Excel! Running your macro...", vbInformation
' Add your desired actions here
End Sub
Public Sub CheckAppActivate()
Dim hwnd As Long
Dim title As String * 255
Dim length As Long
hwnd = GetForegroundWindow()
length = GetWindowText(hwnd, title, Len(title))
If length > 0 Then
title = Left$(title, length)
If InStr(title, "Microsoft Excel") > 0 Then
If Not ActiveCheck Then
ActiveCheck = True
Call RunOnActivate
End If
Else
ActiveCheck = False
End If
End If
' Schedule the next check if the timer is active
If TimerActive Then
Application.OnTime Now + TimeValue("00:00:01"), "CheckAppActivate"
End If
End Sub
Public Sub StartTimer()
TimerActive = True
CheckAppActivate
End Sub
Public Sub StopTimer()
TimerActive = False
End Sub