I have an Excel VBA/Macro that will likely take 20 hours to run. However the computer keeps sleeping and then locking if I don't stay at the computer. How can I keep the computer awake or alive while my VBA runs? I tried adding code to move the mouse around and send mouse clicks. I even tired having a live YouTube stream up.
CodePudding user response:
A program uses SetThreadExecutionState
to ask Windows to not sleep.
SetThreadExecutionState
Enables an application to inform the system that it is in use, thereby preventing the system from entering sleep or turning off the display while the application is running.
The system automatically detects activities such as local keyboard or mouse input, server activity, and changing window focus. Activities that are not automatically detected include disk or CPU activity and video display.
Calling SetThreadExecutionState without ES_CONTINUOUS simply resets the idle timer; to keep the display or system in the working state, the thread must call SetThreadExecutionState periodically.
To run properly on a power-managed computer, applications such as fax servers, answering machines, backup agents, and network management applications must use both ES_SYSTEM_REQUIRED and ES_CONTINUOUS when they process events. Multimedia applications, such as video players and presentation applications, must use ES_DISPLAY_REQUIRED when they display video for long periods of time without user input. Applications such as word processors, spreadsheets, browsers, and games do not need to call SetThreadExecutionState.
You just call it and it applies to the calling thread.
Public Declare Function SetThreadExecutionState Lib "Kernel32" (ByVal esFlags as Long) as Long
Public Const ES_AWAYMODE_REQUIRED = &h40
Public Const ES_CONTINUOUS = &h80000000
Public Const ES_DISPLAY_REQUIRED = &h2
Public Const ES_SYSTEM_REQUIRED = &h1
Public Const ES_USER_PRESENT = &h4
Dim Ret as Long
'System on monitor off
Ret = SetThreadExecutionState(ES_Continuous ES_System_Required ES_Awaymode_Required)
'System and monitor on
Ret = SetThreadExecutionState(ES_Continuous ES_Display_Required ES_Awaymode_Required)
https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setthreadexecutionstate
CodePudding user response:
Try installing Microsoft's free PowerToys utility, then use the Awake portion of that utility. You can read more about it here.