To keep your screen active using VBA, you must use the Windows API function SetThreadExecutionState. This function tells the operating system that the current application requires the system to remain in a working state, effectively preventing the monitor from turning off and the computer from entering sleep mode during the execution of a long-running macro. This is essential for automated reports, data scraping, or long calculations where a locked workstation would interrupt the process or cause the network connection to drop.

What You'll Need

  • A Windows-based PC (this method uses Windows API calls and will not work on macOS).
  • Microsoft Excel, Word, or Access with the Developer tab enabled.
  • Basic familiarity with the Visual Basic Editor (VBE).
  • Administrative rights to run macros if your organization has strict security policies.

Step-by-Step

  1. Open the Visual Basic Editor: Open your Office application and press Alt + F11 on your keyboard. This opens the VBE window where all your code resides.
  2. Insert a New Module: Go to the Insert menu at the top and select Module. This creates a clean space to place the API declarations and the main procedure.
  3. Declare the Windows API: Because the functionality to prevent sleep is not native to the VBA language, you must call the Windows kernel. Paste the following declarations at the very top of the module. Note that the declarations differ based on whether you are using a 32-bit or 64-bit version of Office. Labels and syntax may vary slightly depending on your specific Office build. #If VBA7 Then ' For 64-bit Office Public Declare PtrSafe Function SetThreadExecutionState Lib "kernel32" (ByVal esFlags As Long) As Long #Else ' For 32-bit Office Public Declare Function SetThreadExecutionState Lib "kernel32" (ByVal esFlags As Long) As Long #End If The #If VBA7 block ensures that the code is compatible with both modern 64-bit installations and older 32-bit versions by using the PtrSafe keyword where necessary.
  4. Define the State Constants: To make the code readable, define the flags that tell Windows exactly what to keep active. Add these lines below your declarations: Public Const ES_CONTINUOUS As Long = &H80000000 Public Const ES_DISPLAY_REQUIRED As Long = &H2 Public Const ES_SYSTEM_REQUIRED As Long = &H1 ES_DISPLAY_REQUIRED prevents the monitor from turning off, while ES_SYSTEM_REQUIRED prevents the computer from entering sleep mode. ES_CONTINUOUS ensures the setting stays in effect until the application explicitly changes it or closes.
  5. Create the "Keep Awake" Procedure: Create a subroutine that triggers the active state. Copy this code into your module: Sub PreventSleep() ' This tells Windows to keep the display and system active SetThreadExecutionState ES_CONTINUOUS Or ES_DISPLAY_REQUIRED Or ES_SYSTEM_REQUIRED MsgBox "Screen active mode enabled. The PC will not sleep while this session is open.", vbInformation End Sub
  6. Create the "Allow Sleep" Procedure: It is critical to return the system to its normal power settings once your task is complete, otherwise, the computer will stay awake indefinitely until a reboot or application close. Add this subroutine: Sub AllowSleep() ' This returns the system to normal power management SetThreadExecutionState ES_CONTINUOUS MsgBox "Screen active mode disabled. Normal power settings restored.", vbInformation End Sub
  7. Integrate into Your Main Macro: Instead of running these as standalone buttons, integrate them into your existing automation. Place the PreventSleep call at the start of your main process and the AllowSleep call at the very end. For example: Sub MyLongRunningProcess() Call PreventSleep ' Example: For i = 1 to 1000000: Cells(i, 1) = i: Next i Call AllowSleep End Sub
  8. Test the Implementation: Run your macro. To verify it is working, temporarily set your Windows Power & Sleep settings to turn the screen off after 1 minute. Start the macro and wait; the screen should remain active despite the system setting.

Common Mistakes

One of the most frequent errors is forgetting to include the #If VBA7 conditional compilation. If you use a 64-bit version of Excel but use the 32-bit Declare Function syntax without PtrSafe, the code will throw a compile error immediately upon opening the workbook. Always use the conditional block to ensure the tool works across different user environments.

Another common mistake is neglecting the AllowSleep procedure. If your macro crashes or is stopped manually via Ctrl + Break before it reaches the AllowSleep call, the ES_CONTINUOUS flag remains active in the Windows kernel for that thread. This means your computer will not sleep even after you close the macro, which can lead to unnecessary power consumption or security risks in an office environment where screens should lock automatically.

Users also frequently confuse ES_DISPLAY_REQUIRED with ES_SYSTEM_REQUIRED. If you only use ES_SYSTEM_REQUIRED, the computer's CPU will keep running, but the monitor will still go black. If your macro requires an active visual interface or if you need to monitor the progress visually, you must include the display flag.

Tips

For maximum reliability, wrap your main process in an error handler. By using On Error GoTo ErrorHandler, you can ensure that even if the macro fails midway, the code jumps to a section that calls AllowSleep before ending. This prevents the "zombie awake" state where the PC refuses to sleep because of a crashed macro.

If you are distributing this tool to other users, consider adding a toggle button on a worksheet. This allows users to manually enable or disable the keep-awake feature without entering the VBA editor. You can link the button to the PreventSleep and AllowSleep macros respectively.

To avoid triggering corporate IT alerts regarding "stay-awake" software, keep the use of this API limited to the duration of the actual task. Using a loop to simulate keystrokes (like sending the F15 key) is an older method that is often detected by security software as "mouse jiggling" or unauthorized activity; the SetThreadExecutionState API is the official Windows method and is generally more discreet and stable.

Troubleshooting

If the screen still turns off despite the code running, first check if your organization has a Group Policy (GPO) that overrides local application requests. Some high-security environments force a screen lock after a specific period regardless of what the software requests. If this is the case, the API call will be ignored by the OS.

If you encounter a "Compile error: Type mismatch" or "Invalid procedure call," double-check your Long and LongPtr declarations. In 64-bit VBA, pointers should technically be LongPtr, though for this specific API function, Long usually suffices for the flags. Ensure the #If VBA7 logic is correctly placed at the very top of the module, before any other subroutines.

If the macro runs but the computer sleeps anyway, verify that you are using ES_CONTINUOUS. Without this flag, the request to keep the system awake is only valid for a very short window and will not persist throughout the duration of a long loop or data import process.

Frequently Asked Questions

Does this code work on a Mac?

No, this code relies on kernel32.dll, which is a core component of the Windows operating system. macOS uses entirely different system calls for power management, and VBA for Mac cannot access the Windows API.

Will this prevent my computer from locking?

It prevents the system from entering sleep and the monitor from turning off. However, if your company has a security policy that forces a lock based on an inactivity timer (which monitors actual mouse/keyboard input), this API may not bypass that lock, as it only tells Windows the system is "busy," not that a human is interacting with it.

Is this considered "malware" or a "jiggler"?

No. This is a legitimate Windows API used by media players (like VLC) and presentation software (like PowerPoint) to prevent the screen from going dark during a movie or slideshow. It does not simulate fake input; it simply communicates the application's needs to the OS.

Can I use this to keep a remote desktop session alive?

Yes, in many cases, this will prevent the local machine from sleeping, which in turn keeps the network connection to the remote server active. However, the remote server itself may have its own independent timeout settings that this local VBA code cannot control.

Does this use a lot of CPU or RAM?

No. The API call is a simple flag sent to the Windows kernel. It consumes virtually no system resources and does not slow down the execution of your other VBA code.