Using VBA To Lock The PC

Ever needed or wanted to be able to lock the PC? Perhaps after running your code?

Well it is surprisingly simple to do!

Luckily for us, there is a simple API we can implement to do all the heavy lifting. All we need to do is build a simple wrapper function around it as demonstrated below:

#If VBA7 Then
    Private Declare PtrSafe Function LockWorkStation Lib "user32.dll" () As Long
#Else
    Declare Function LockWorkStation Lib "user32.dll" () As Long
#End If


'---------------------------------------------------------------------------------------
' Procedure : LockPC
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Lock the current PC (this does not logoff the user, simply lock the session)
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: None required
' Dependencies: LockWorkStation API Declaration(s)
'
' Usage:
' ~~~~~~
' Call LockPC
'
' ? LockPC
'   Returns -> True  : when successful
'              False : when it fails to lock the PC
'
' Revision History:
' Rev       Date(yyyy-mm-dd)        Description
' **************************************************************************************
' 1         2024-04-11              Initial Public Release
'                                   Added Function header
'---------------------------------------------------------------------------------------
Public Function LockPC() As Boolean
On Error GoTo Error_Handler
    Dim lRet                  As Long
    
    lRet = LockWorkStation
    If lRet = 0 Then
        Debug.Print "Couldn't lock the PC for an unknown reason."
        Debug.Print Err.LastDllError 'to get more details on the error itself
    Else
        LockPC = True
        Debug.Print "PC Successfully locked!"
    End If
    
Error_Handler_Exit:
    On Error Resume Next
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Source: LockPC" & 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

As shown in the function header, using it can be achieved by simply doing:

If LockPC Then
    'Lock PC Call was successful
Else
    'Lock PC Call was NOT successful
End if

Or perhaps something more like:

If Not LockPC Then
    Exit Sub
    'Exit Function
End if

and that’s all there is to it.
 

Other Resources On The Subject