Please, use the next function, able to return the last ShutDown time as Local time. The code, as it is, needs a reference to 'Microsoft WMI Scripting V1.2 Library'. It can be run without it, declaring all involved variables/objects As Object (Late binding). But adding the respective reference offers intellisense suggestions and it can be used for more tasks:
Function GetLastShutdownTime() As Date
'It needs a reference to 'Microsoft WMI Scripting V1.2 Library'
Dim DateTime As WbemScripting.SWbemDateTime 'Object
Dim objWMIService As WbemScripting.SWbemServicesEx 'Object
Dim colEvents As WbemScripting.SWbemObjectSet ' Object
Dim objEvent As WbemScripting.SWbemObjectEx ' Object
' Get WMI service object:
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
' Create a new datetime object.
Set DateTime = CreateObject("WbemScripting.SWbemDateTime")
' Query for events having EventCode=1074 (shutdown events). They are returnded from the last one to the first:
Set colEvents = objWMIService.ExecQuery("SELECT * FROM Win32_NTLogEvent WHERE LogFile='System' AND EventCode=1074")
' Iterate through the events to find last shutdown (the first one found):
For Each objEvent In colEvents
Debug.Print objEvent.timegenerated 'it rturns the last shutDown as GMT (string) time!
DateTime.value = objEvent.TimeGenerated 'place the GMT found time as DateTime value
'return the event date time as LOCAL TIME:
GetLastShutdownTime = DateTime.GetVarDate: Exit For
Next objEvent
' Clean up memory
Set objWMIService = Nothing: Set colEvents = Nothing: Set objEvent = Nothing: Set DateTime = Nothing
End Function
If adding the required reference looks difficult, I can place a piece of code able to add it automatically. In fact, I will post it now:
Private Sub WVIScriptingFromFile()
'Microsoft WMI Scripting V1.2 Library'...
On Error Resume Next
ThisWorkbook.VBProject.References.AddFromFile "c:\Windows\System32\wbem\wbemdisp.TLB"
If Err.number <> 0 Then
MsgBox "The reference already exists..."
Else
MsgBox "The reference added successfully..."
End If
On Error GoTo 0
End Sub
The above function can be tested using the next Sub:
Sub TestGetLastShutdownTime()
Debug.Print GetLastShutdownTime
End Sub
Please, send some feedback after testing it.