0

The following code is using for measuring CPU % usage.

Public Sub Macro1()

Dim strComputer As String
Dim objWMIService As Object
Dim colItems As Object
Dim objItem As Object

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor", , 48)

For Each objItem In colItems
    Debug.Print objItem.PercentProcessorTime
Next
    
End Sub

I have got the above code from this link: https://analystcave.com/excel-measuring-cpu-usage-in-vba-and-other-performance-metrics/#comment-184350.

How to wait until the CPU usage drops below 60% in VBA?

1
  • 3
    The code in the post queries the WMI data only once. As far as I know, it's not possible to request streamed data from WMI. The author of the article runs the macro with a 2-second timed cron job (presumably not cron, but rather a setting within the macro). To determine when CPU usage exceeds 60%, you need to query the CPU every 1-2 seconds until the result reaches 60% or higher. Commented Mar 10 at 7:49

2 Answers 2

1

you could try something like this:

(I would probably put a Sleep() in there too to help reduce it spinning to fast)

Sub Test()

    Debug.Print "Starting"
    Call PauseWhileBusy
    Debug.Print "Done"

End Sub

Sub PauseWhileBusy(Optional ByVal lMaxPercent As Long = 60, Optional ByVal strComputer As String = ".")
    
    Dim colItems As Object
    Dim objItem As Object
    Dim bTooBusy As Boolean
    
    With GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
        Do
            Set colItems = .ExecQuery("Select * from Win32_Processor")
            For Each objItem In colItems
                Debug.Print "Current Load:", objItem.LoadPercentage
                bTooBusy = objItem.LoadPercentage > lMaxPercent
            Next
            DoEvents
        Loop While bTooBusy
        
    End With
End Sub
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Joe Bourne Your code is perfect! Thank you very much. I dont know if Sleep() is necessary or not. If you have free time, I need other codes regarding Memory Usage and Disk Usage. Thanks in advance.
-1

You can achieve this by running a loop that continuously checks the CPU usage and only exits when it drops below 60%. To prevent excessive CPU usage while waiting, you should use Sleep to introduce a small delay between checks and DoEvents to keep the system responsive.

1 Comment

Welcome to Stack Overflow. Please read How to Answer. This answer vaguely describes a possible solution, which isn't very clear. An example would really help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.