Excel VBA: Can my VBA code determine whether Solver is running?

Dave Post 0 Reputation points
2025-08-09T18:42:52.5233333+00:00

Is there a way to test whether Solver is running? I have a section of VBA code that must be skipped if Solver is running.

I'm using MS Office LTSC Professional Plus 2024 (Windows).

Developer technologies | VB
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Varsha Dundigalla(INFOSYS LIMITED) 795 Reputation points Microsoft External Staff
    2025-08-11T06:41:34.9766667+00:00

    Thank you for reaching out. Please find the answer below.

    In Excel VBA, there is no built-in method to directly detect if Solver is currently running. Solver runs synchronously, meaning that when you invoke it with SolverSolve, VBA execution pauses until Solver finishes. There is no property or event you can check mid-run. To create a robust solution that works whether Solver is run manually or via VBA, you can combine several strategies:

    1. Check Solver Activity
    Create a named cell in your workbook, for example SolverStatus. Before starting Solver, set the value to "Running". After Solver completes, set it back to "Idle". In any of your event-driven or calculation-sensitive code, check this flag:

    If Range("SolverStatus").Value <> "Running" Then
        ' Safe to run your logic
    End If
    

    2. Manual Solver Runs
    Before running Solver manually, set:

    Range("SolverStatus").Value = "Running"
    Range("SolverStatus").Value = "Idle"
    
    Sub PrepareSolverRun()
        Range("SolverStatus").Value = "Running"
        MsgBox "Solver status set to Running. Please run Solver manually now."
    End Sub
    

    3. Passive Detection via Cell Monitoring (Optional)
    If Solver changes a known cell, you can monitor that cell on a timer and update the status flag when it changes:

    Public LastValue As Variant
    
    Sub StartMonitoring()
        LastValue = Range("TargetCell").Value
        Application.OnTime Now + TimeValue("00:00:01"), "CheckSolverActivity"
    End Sub
    
    Sub CheckSolverActivity()
        If Range("TargetCell").Value <> LastValue Then
            Range("SolverStatus").Value = "Running"
            LastValue = Range("TargetCell").Value
        End If
        Application.OnTime Now + TimeValue("00:00:01"), "CheckSolverActivity"
    End Sub
    

    This method is heuristic and works best if Solver is expected to update a specific cell.
    4. VBA-Controlled Solver Runs
    If you run Solver from VBA, you can also use a Boolean variable along with the named cell:

    Public SolverWasJustRun As Boolean
    
    Sub RunSolver()
        SolverWasJustRun = True
        Range("SolverStatus").Value = "Running"
        SolverSolve UserFinish:=True
        SolverWasJustRun = False
        Range("SolverStatus").Value = "Idle"
    End Sub
    

    By using a named cell flag for manual runs, a Boolean flag for VBA-controlled runs, and optional passive detection for known cell changes, you can make your code skip execution safely during Solver’s activity in all scenarios.
    Let us know if the issue persists after following these steps. We’ll be happy to assist further if needed.

    0 comments No comments

  2. Dave Post 0 Reputation points
    2025-08-11T17:16:38.59+00:00

    Your third solution comes closest to doing what I need but provides no way to determine when Solver isn't running so, once set, there's no way to know when to clear the flag.

    The others require the user to do something extra before running Solver, which makes detection easy but is clumsy. Running Solver from within VBA would also make it easy, but would mean the user couldn't run Solver normally and I'd have to provide an interface for setting it options.

    I was hoping for a way to issue a system call (to Task Manager, maybe).

    0 comments No comments

  3. Varsha Dundigalla(INFOSYS LIMITED) 795 Reputation points Microsoft External Staff
    2025-08-12T08:34:39.2333333+00:00

    Thank you for reaching out please find the answer below.

    There’s no built-in way in VBA to detect when Solver is running, but you can work around it by using a flag variable when triggering Solver from your own code.

    Standard Module Code

    '======================= SOLVER STATUS DETECTOR =======================
    ' Paste into STANDARD MODULE (Alt+F11 > Insert > Module)
    Option Explicit
    
    ' Configuration - MUST CUSTOMIZE THESE
    Private Const TARGET_CELL_ADDRESS As String = "A1"  ' Change to cell Solver modifies
    Private Const TIMEOUT_SECONDS As Integer = 3        ' Adjust based on Solver speed
    
    ' System variables
    Private NextCheckTime As Date
    Private PreviousValue As Variant
    Private MonitorActive As Boolean
    
    ' Initialize detection system
    Public Sub InitSolverDetection()
        SetupSolverStatusCell
        StartSolverMonitor
    End Sub
    
    ' Start monitoring loop
    Public Sub StartSolverMonitor()
        MonitorActive = True
        PreviousValue = GetTargetCellValue()
        ScheduleNextCheck
    End Sub
    
    ' Core detection logic
    Public Sub CheckSolverActivity()
        If Not MonitorActive Then Exit Sub
    
        On Error GoTo Cleanup
        Dim currentValue As Variant
        currentValue = GetTargetCellValue()
    
        With Range("SolverStatus")
            ' Detect Solver activity
            If currentValue <> PreviousValue Then
                .Value = "Running"
                PreviousValue = currentValue
            ' Auto-clear after timeout
            ElseIf .Value = "Running" And IsSolverInactive() Then
                .Value = "Idle"
            End If
        End With
    
    Cleanup:
        ScheduleNextCheck
    End Sub
    
    ' Safe Solver runner
    Public Sub RunSolverSafely()
        Range("SolverStatus").Value = "Running"
        SolverSolve UserFinish:=True
    End Sub
    
    ' Setup status cell
    Private Sub SetupSolverStatusCell()
        On Error Resume Next
        ThisWorkbook.Names.Add Name:="SolverStatus", RefersTo:="=$Z$100"
        Range("SolverStatus").Value = "Idle"
        On Error GoTo 0
    End Sub
    
    ' Stop monitoring safely
    Public Sub StopSolverMonitor()
        MonitorActive = False
        On Error Resume Next
        Application.OnTime NextCheckTime, "CheckSolverActivity", , False
        On Error GoTo 0
    End Sub
    
    '=============== ENHANCED HELPER FUNCTIONS ===============
    Private Function GetTargetCellValue() As Variant
        On Error Resume Next
        GetTargetCellValue = Range(TARGET_CELL_ADDRESS).Value
        If Err.Number <> 0 Then
            ' Fallback to status cell if target missing
            GetTargetCellValue = Range("SolverStatus").Value
            Err.Clear
        End If
        On Error GoTo 0
    End Function
    
    Private Function IsSolverInactive() As Boolean
        ' Use DateDiff to avoid midnight issues
        IsSolverInactive = DateDiff("s", Now - TimeValue("00:00:01"), Now) >= TIMEOUT_SECONDS
    End Function
    
    Private Sub ScheduleNextCheck()
        If MonitorActive Then
            NextCheckTime = Now + TimeValue("00:00:01")
            Application.OnTime NextCheckTime, "CheckSolverActivity"
        End If
    End Sub
    

    ThisWorkbook Module Code

    '==== PASTE INTO "ThisWorkbook" MODULE ====
    Private Sub Workbook_Open()
        InitSolverDetection
    End Sub
    
    Private Sub Workbook_BeforeClose(Cancel As Boolean)
        StopSolverMonitor
    End Sub
    

    Key Improvements:

    Midnight-Safe Timeout Detection

    ' OLD:
    ' (Timer - LastChangeTime) > TIMEOUT_SECONDS
    
    ' NEW:
    DateDiff("s", Now - TimeValue("00:00:01"), Now) >= TIMEOUT_SECONDS
    

    Safer OnTime Management

    Public Sub StopSolverMonitor()
        MonitorActive = False
        Application.OnTime NextCheckTime, "CheckSolverActivity", , False
    End Sub
    

    Error-Proof Cell Access

    Private Function GetTargetCellValue() As Variant
        On Error Resume Next
        GetTargetCellValue = Range(TARGET_CELL_ADDRESS).Value
        If Err.Number <> 0 Then
            GetTargetCellValue = Range("SolverStatus").Value
        End If
    End Function
    

    Scheduled Check Tracking

    Private Sub ScheduleNextCheck()
        If MonitorActive Then
            NextCheckTime = Now + TimeValue("00:00:01")
            Application.OnTime NextCheckTime, "CheckSolverActivity"
        End If
    End Sub
    

    Setup & Usage:

    Configuration (Paste in Standard Module)

    Private Const TARGET_CELL_ADDRESS As String = "A1"  ' ← YOUR SOLVER-MODIFIED CELL
    Private Const TIMEOUT_SECONDS As Integer = 3        ' ← ADJUST BASED ON SOLVER SPEED
    

    Status Check (Use Anywhere in Your Code)

    If Range("SolverStatus").Value <> "Running" Then
        ' Safe to execute sensitive code
    End If
    

    Run Solver

    RunSolverSafely  ' For VBA runs
    ' Or use normal Solver UI - detection works automatically!
    

     Why This is Better:

    1. No Midnight Glitches  

       Uses calendar-aware time comparisons instead of Timer

    1. No Zombie Processes  

       Properly cancels scheduled checks when workbook closes

    1. Fails Gracefully  

       Handles invalid/missing target cells without crashing 

    1. Same Simple Setup 

       Still just 2 code blocks to paste + cell configuration

    This version maintains all original functionality while adding robustness for edge cases and long-running workbooks.

    Let us know if you need any further help with this. We’ll be happy to assist further if needed.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.