copy

Saturday, 30 June 2018



Last updated: 03/07/2018, 1 min read (without the code)

Get Laptop Battery Information Through VBA


Introduction



As the title indicates, in this post we will learn how to get several properties related to the battery of the laptop that runs our VBA code. Unfortunately, VBA does not have any built-in functionality that can be used to retrieve this kind of information. Therefore, with the help of WMI we will get the following battery properties:
  • Availability
  • Battery status
  • Chemistry
  • Estimated charge remaining
  • Estimated run time
  • Time on battery
  • Time to full charge

These are probably the most useful ones. If you need other attributes, you can check this link to find the additional properties that are available in the Win32_Battery class. The technique to retrieve any of the other property is similar to the one used below.



VBA code



The code was written in a way that all the functions are based on the GetBatteryObject function, which returns an object containing several properties about the laptop's battery. The other functions simply use this object to check if a particular property exists. If yes, then they retrieve the value of that property. If the returned numeric value is an enumeration, as it is in the case of GetBatteryAvailability, GetBatteryStatus and GetBatteryChemistry functions, the code returns the actual string value. In the other cases, the functions return the numeric value that corresponds either to a charge percentage or to time (minutes/seconds).

Option Explicit

'-------------------------------------------------------------------------------------------
'This module contains some functions for retrieving information about the laptop's battery.
'The main function is the GetBatteryObject, which retrieves an object containing several
'properties about the laptop's battery. The other functions simply use this object to
'retrieve the appropriate property. The GetBatteryObject function uses WMI to query
'the Win32_Battery class of Windows. More information about this class can be found in:
'https://docs.microsoft.com/en-us/windows/desktop/cimwin32prov/win32-battery

'Written By:    Christos Samaras
'Date:          30/06/2018
'Last Updated:  03/07/2018
'E-mail:        xristos.samaras@gmail.com
'Site:          https://www.myengineeringworld.net
'-------------------------------------------------------------------------------------------

Private Function GetBatteryObject() As Object
    
    '----------------------------------------------------------------------------
    'Returns an object containing several properties about the laptop's battery.
    'The function is private, so as to not be visible from Excel worksheets.
    '----------------------------------------------------------------------------
    
    'Declaring the necessary variables.
    Dim computer    As String
    Dim wmiService  As Object
    Dim colItems    As Object
    Dim item        As Object
    
    On Error Resume Next
    
    'Set the computer.
    computer = "."
    
    'The root\cimv2 namespace is used to access the Win32_Battery class.
    Set wmiService = GetObject("winmgmts:\\" & computer & "\root\cimv2")
    
    'A select query is used to get a collection of battery objects.
    Set colItems = wmiService.ExecQuery("SELECT * FROM Win32_Battery", , 48)
    
    'Note, an alternative here will be to select only the properties you need and not all (the asterisk means all).
    'In that case, the query could be written like this:
    'Set colItems = wmiService.ExecQuery("SELECT Availability, BatteryStatus, Chemistry," + _
                                                "EstimatedChargeRemaining, EstimatedRunTime," + _
                                                "TimeOnBattery, TimeToFullCharge FROM Win32_Battery", , 48)
        
    'Get the first object that is not null.
    For Each item In colItems
        If Not IsNull(item) Then Set GetBatteryObject = item
        Exit Function
    Next
    
    'If no battery object is found, return nothing.
    Set GetBatteryObject = Nothing

    On Error GoTo 0
    
End Function

Public Function GetBatteryAvailability() As String
    
    '-----------------------------------------
    'Returns the availability of the battery.
    '-----------------------------------------
    
    'Declaring the necessary variables.
    Dim batteryObject   As Object
    Dim i               As Integer
            
    On Error Resume Next
    
    'Get the battery object.
    Set batteryObject = GetBatteryObject()
    If Not IsObject(batteryObject) Then
        GetBatteryAvailability = "Battery Object Error"
        Exit Function
    End If
    
    'Check if the Availability property can be retrieved.
    If IsNull(batteryObject.Availability) Then
        GetBatteryAvailability = "Battery Property Error"
        Exit Function
    End If
    
    'Get the numeric value from the property.
    i = CInt(batteryObject.Availability)
    If i < 1 Or i > 21 Then
        GetBatteryAvailability = "Battery Availability Error"
        Exit Function
    End If
    
    'Use the numeric value to return the actual string value.
    GetBatteryAvailability = Array("Other", "Unknown", "Running/Full Power", "Warning", "In Test", "Not Applicable", _
                                   "Power Off", "Off Line", "Off Duty", "Degraded", "Not Installed", "Install Error", _
                                   "Power Save - Unknown", "Power Save - Low Power Mode", "Power Save - Standby", _
                                   "Power Cycle", "Power Save - Warning", "Paused", "Not Ready", "Not Configured", _
                                   "Quiesced")(i - 1)
    
    'Release the battery object.
    Set batteryObject = Nothing
    
    On Error GoTo 0
    
End Function

Public Function GetBatteryStatus() As String
    
    '-----------------------------------
    'Returns the status of the battery.
    '-----------------------------------
    
    'Declaring the necessary variables.
    Dim batteryObject   As Object
    Dim i               As Integer
            
    On Error Resume Next
    
    'Get the battery object.
    Set batteryObject = GetBatteryObject()
    If Not IsObject(batteryObject) Then
        GetBatteryStatus = "Battery Object Error"
        Exit Function
    End If
    
    'Check if the BatteryStatus property can be retrieved.
    If IsNull(batteryObject.BatteryStatus) Then
        GetBatteryStatus = "Battery Property Error"
        Exit Function
    End If
    
    'Get the numeric value from the property.
    i = CInt(batteryObject.BatteryStatus)
    If i < 1 Or i > 11 Then
        GetBatteryStatus = "Battery Status Error"
        Exit Function
    End If
    
    'Use the numeric value to return the actual string value.
    GetBatteryStatus = Array("Discharging", "On A/C", "Fully Charged", "Low", "Critical", "Charging", "Charging High", _
                             "Charging Low", "Charging Critical", "Undefined", "Partially Charged")(i - 1)
    
    'Release the battery object.
    Set batteryObject = Nothing
    
    On Error GoTo 0

End Function

Public Function GetBatteryChemistry() As String
    
    '---------------------------------
    'Returns the battery's chemistry.
    '---------------------------------
    
    'Declaring the necessary variables.
    Dim batteryObject   As Object
    Dim i               As Integer
            
    On Error Resume Next
    
    'Get the battery object.
    Set batteryObject = GetBatteryObject()
    If Not IsObject(batteryObject) Then
        GetBatteryChemistry = "Battery Object Error"
        Exit Function
    End If
    
    'Check if the Chemistry property can be retrieved.
    If IsNull(batteryObject.Chemistry) Then
        GetBatteryChemistry = "Battery Property Error"
        Exit Function
    End If
    
    'Get the numeric value from the property.
    i = CInt(batteryObject.Chemistry)
    If i < 1 Or i > 11 Then
        GetBatteryChemistry = "Battery Chemistry Error"
        Exit Function
    End If
    
    'Use the numeric value to return the actual string value.
    GetBatteryChemistry = Array("Other", "Unknown", "Lead Acid", "Nickel Cadmium", "Nickel Metal Hydride", _
                                "Lithium-ion", "Zinc air", "Lithium Polymer")(i - 1)
    
    'Release the battery object.
    Set batteryObject = Nothing
    
    On Error GoTo 0
    
End Function

Public Function GetEstimatedChargeRemaining() As Integer
    
    '-------------------------------------------------------------
    'Returns the remaining charge of the battery as a percentage.
    'A value of 100 means that the battery is fully charged.
    '-------------------------------------------------------------
    
    'Declaring the necessary variable.
    Dim batteryObject   As Object
            
    On Error Resume Next
    
    'Get the battery object.
    Set batteryObject = GetBatteryObject()
    If Not IsObject(batteryObject) Then
        GetEstimatedChargeRemaining = "Battery Object Error"
        Exit Function
    End If
    
    'Check if the EstimatedChargeRemaining property can be retrieved.
    If IsNull(batteryObject.EstimatedChargeRemaining) Then
        GetEstimatedChargeRemaining = "Battery Property Error"
        Exit Function
    End If
    
    'Get the numeric value from the property.
    GetEstimatedChargeRemaining = CInt(batteryObject.EstimatedChargeRemaining)
    
    'Release the battery object.
    Set batteryObject = Nothing
    
    On Error GoTo 0
    
End Function

Public Function GetEstimatedRunTime() As Long
    
    '------------------------------------------------------------------------------------------------------------
    'Returns the time (in minutes) to battery charge depletion under the present load conditions if the utility
    'power is off, or lost and remains off, or the laptop is disconnected from a power source.
    'A value of 30 means that the battery can continue providing power to your laptop for about 30 minutes.
    '------------------------------------------------------------------------------------------------------------
    
    'Declaring the necessary variable.
    Dim batteryObject   As Object
            
    On Error Resume Next
    
    'Get the battery object.
    Set batteryObject = GetBatteryObject()
    If Not IsObject(batteryObject) Then
        GetEstimatedRunTime = "Battery Object Error"
        Exit Function
    End If
        
    'Check if the EstimatedRunTime property can be retrieved.
    If IsNull(batteryObject.EstimatedRunTime) Then
        GetEstimatedRunTime = "Battery Property Error"
        Exit Function
    End If
    
    'Get the numeric value from the property.
    GetEstimatedRunTime = CLng(batteryObject.EstimatedRunTime)
    
    'Release the battery object.
    Set batteryObject = Nothing
    
    On Error GoTo 0
    
End Function

Public Function GetTimeOnBattery() As Long
        
    '------------------------------------------------------------------------------------------------------------------
    'Returns the elapsed time (in seconds) since the computer system's UPS last switched to battery power or the time
    'since the system or UPS was last restarted, whichever is less. If the battery is "online", 0 (zero) is returned.
    '------------------------------------------------------------------------------------------------------------------
    
    'Declaring the necessary variable.
    Dim batteryObject   As Object
            
    On Error Resume Next
    
    'Get the battery object.
    Set batteryObject = GetBatteryObject()
    If Not IsObject(batteryObject) Then
        GetTimeOnBattery = "Battery Object Error"
        Exit Function
    End If
    
    'Check if the TimeOnBattery property can be retrieved.
    If IsNull(batteryObject.TimeOnBattery) Then
        GetTimeOnBattery = "Battery Property Error"
        Exit Function
    End If
    
    'Get the numeric value from the property.
    GetTimeOnBattery = CLng(batteryObject.TimeOnBattery)
    
    'Release the battery object.
    Set batteryObject = Nothing
    
    On Error GoTo 0
    
End Function

Public Function GetTimeToFullCharge() As Long
    
    '-------------------------------------------------------------------------------------------------------------
    'Returns the remaining time (in minutes) to charge the battery fully at the current charging rate and usage.
    'A value of 45 means that the battery will be fully charged in about 45 minutes.
    '-------------------------------------------------------------------------------------------------------------
    
    'Declaring the necessary variable.
    Dim batteryObject   As Object
            
    On Error Resume Next
    
    'Get the battery object.
    Set batteryObject = GetBatteryObject()
    If Not IsObject(batteryObject) Then
        GetTimeToFullCharge = "Battery Object Error"
        Exit Function
    End If
    
    'Check if the TimeToFullCharge property can be retrieved.
    If IsNull(batteryObject.TimeToFullCharge) Then
        GetTimeToFullCharge = "Battery Property Error"
        Exit Function
    End If
    
    'Get the numeric value from the property.
    GetTimeToFullCharge = CLng(batteryObject.TimeToFullCharge)
    
    'Release the battery object.
    Set batteryObject = Nothing
    
    On Error GoTo 0
    
End Function

The above code is contained in the sample workbook that you will find in the Downloads section that follows. As a bonus tip, you will also find there a "battery chart" that shows the remaining charge of your laptop's battery.



Downloads



Download

The file can be opened with Excel 2007 or newer. Please enable macros before using it.

Did you like this post? If yes, then share it with your friends. Thank you!


Categories:


Mechanical Engineer (Ph.D. cand.), M.Sc. Cranfield University, Dipl.-Ing. Aristotle University, Thessaloniki - Greece.
Communication: e-mail, Facebook, Twitter, Google+ and Linkedin. More info