
Uso de VBA para apagar, reiniciar, hibernar y cerrar sesión en una PC
¿Alguna vez necesitaste apagar, reiniciar, hibernar tu PC… después de ejecutar algún código?
Como ocurre con la mayoría de las cosas, hay varios enfoques posibles, pero hoy pensé en demostrar una solución muy simple usando el comando Shutdown:


A continuación se presentan algunos procedimientos sencillos para realizar acciones individuales:
Desconectarse
Public Function PC_LogOff() As Boolean
Dim vRetVal As Variant
vRetVal = Shell("shutdown /l /f")
If vRetVal 0 Then PC_LogOff = True
End Function
Hibernar
Public Function PC_Hibernate() As Boolean
Dim vRetVal As Variant
vRetVal = Shell("shutdown /h")
If vRetVal 0 Then PC_Hibernate = True
End Function
Reanudar
Public Function PC_Restart() As Boolean
Dim vRetVal As Variant
vRetVal = Shell("shutdown /r /f")
If vRetVal 0 Then PC_Restart = True
End Function
Cerrar
Public Function PC_Shutdown() As Boolean
Dim vRetVal As Variant
vRetVal = Shell("shutdown /s /f")
If vRetVal 0 Then PC_Shutdown = True
End Function
Una función para gobernarlos a todos
Sabiendo lo anterior, siempre podríamos combinar cosas en una única función versátil como:
Enum PC_ShutdownCommand
Shutdown_LogOff = 1
Shutdown_Hibernate = 2 'has to be enabled on the system to work!
Shutdown_Restart = 3
Shutdown_Shutdown = 4
End Enum
'---------------------------------------------------------------------------------------
' Procedure : PC_Shutdown2
' Author : Daniel Pineault, CARDA Consultants Inc.
' Website :
' Purpose : Initiate one of the Shutdown commands (hybernate, restart, shutdown, logoff)
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
' (CC BY-SA 4.0) -
' Req'd Refs: Late Binding -> None required
' References:
'
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' lCmd : PC_ShutdownCommand Enum value of the command to issue
'
' Usage:
' ~~~~~~
' PC_Shutdown2(Shutdown_Hibernate)
' Returns -> True is successful
' False is the command couldn't be executed for some reason
'
' Revision History:
' Rev Date(yyyy-mm-dd) Description
' **************************************************************************************
' 1 2024-04-13 Initial Release
' Added Procedure header and error handler
'---------------------------------------------------------------------------------------
Function PC_Shutdown2(lCmd As PC_ShutdownCommand) As Boolean
On Error GoTo Error_Handler
Dim sCmd As String
Dim vRetVal As Variant
Select Case lCmd
Case Shutdown_LogOff
sCmd = "/l /f"
Case Shutdown_Hibernate
sCmd = "/h"
Case Shutdown_Restart
sCmd = " /r /f"
Case Shutdown_Shutdown
sCmd = "/s /f"
End Select
If sCmd "" Then
vRetVal = Shell("shutdown " & sCmd)
If vRetVal 0 Then PC_Shutdown2 = True
End If
Error_Handler_Exit:
On Error Resume Next
Exit Function
Error_Handler:
MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
"Error Source: PC_Shutdown2" & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occurred!"
Resume Error_Handler_Exit
End Function
Mas opciones
Tenga en cuenta que el comando Apagado ofrece una multitud de parámetros. En mis ejemplos he simplificado mucho las cosas, pero puede añadir fácilmente demoras, reiniciar en el menú de opciones, etc.
Utilice esto como punto de partida y siéntase libre de llevar las cosas más allá para satisfacer las necesidades de su proyecto.