Excel VBA Shutdown Computer
Note: Save all your unsaved Documents before Testing this Code
There is no escaping with this code. This VBA Shutdown, log off or Reboot the computer, sometimes, even without asking you for any confirmation to save the unsaved work. Always save your “in progress” work and then hit run.
I myself ended up in rebooting the system with this code multiple times, before I publish this code. Good that I saved all my MS Word, Excel and Notepad documents that I was working on.
Where can we use this?
- Save Power: Many times, we leave office just by locking the computer. The electricity is still used up to keep the desktops up and running. You can use this code to set a time limit (example: 10.00 pm or 11.00 pm) in excel and if that time limit is reached, this code can be used to shutdown workstations.
- Limit Working Hours: Are you so addicted to sit for long time with computer at home. Set a time limit to shutdown and spend some time with Family.
Well, I have given 2 examples. Now use your imagination further to find where this code can be used. If you come up with any interesting usage with this code, post your comments or article link at comments section.
Lets get to the actual Excel VBA PC shutdown code. The same code can be used in VB also.Visual Basic12345678910111213141516171819202122232425262728293031323334'Excel VBA code to Shutdown Computer'For More Info search for these Windows Keywords'EWX_LogOff'EWX_SHUTDOWN'EWX_REBOOT'EWX_FORCE'EWX_POWEROFF'ExitWindowsEx Windows API Function to perform the following'in Computers running with Windows Operating System'(1) Logs off - Code: 0'(2) Shuts down - Code: 1'(3) Reboot - Code: 2'(4) Forced Process - Code: 4'(4) Power Off - Code: 8'(5) Force if Hung - Code: 10''''API Function DeclarationPublic Declare Function ExitWindowsEx Lib "user32" _(ByVal dwOptions As Long, _ByVal dwReserved As Long) As Long''''Call the below Functions to Perform Log off or Shutdown or RebootPrivate Sub Excel_VBA_Log_Off_Computer()ExitWindowsEx 4, 0End SubPrivate Sub Excel_VBA_ShutDown_Computer()ExitWindowsEx 1, 0End SubPrivate Sub Excel_VBA_Reboot_Computer()ExitWindowsEx 2, 0End Sub
Note: Add the force flag code to normal process code to force complete an operation.
For example: If you want a normal shutdown use ‘1’. If it is force Shutdown then use ‘5’ i.e., Shutdown Code(1) + Force Complete Code(4).
Steps to Execute the VBA Shutdown Code
- Create a new workbook and press Alt F11 to view VB Editor.
- Copy and paste the above code.
- Save this workbook as Macro Enables workbook and also, save all other unsaved documents.
- Execute the code by pressing Alt F5. System will start to Log off.
Excel VBA to Shutdown Computer or Logoff User