You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于条件逻辑自动选择运行Excel Solver的VBA实现需求

基于条件逻辑自动运行对应Excel Solver的VBA实现

前置准备

  • 打开VBA编辑器(快捷键:Alt+F11)
  • 点击菜单栏「工具」→「引用」
  • 在弹出的引用窗口中,勾选Solver(对应文件通常为Solver.xlam),点击「确定」

完整代码实现

Sub RunSolverByCondition()
    ' 清理之前的Solver约束,避免旧配置干扰新求解
    SolverReset
    
    ' 核心条件判断:A1值大于B1时运行Solver1,否则运行Solver2
    If Range("A1").Value > Range("B1").Value Then
        ' --- Solver1 具体逻辑 ---
        SolverAdd CellRef:="$AC$79:$AD$79", Relation:=1, FormulaText:="100"
        SolverAdd CellRef:="$AE$79", Relation:=2, FormulaText:="0"
        SolverAdd CellRef:="$AF$79", Relation:=2, FormulaText:="2"
        SolverAdd CellRef:="$AG$79", Relation:=2, FormulaText:="0"
        SolverAdd CellRef:="$X$79", Relation:=1, FormulaText:="10"
        SolverAdd CellRef:="$AB$79", Relation:=1, FormulaText:="10"
        SolverAdd CellRef:="$Y$79:$AA$79", Relation:=1, FormulaText:="100"
        SolverAdd CellRef:="$X$79:$AD$79", Relation:=4, FormulaText:="integer"
        SolverOk SetCell:="$CQ$4", MaxMinVal:=1, ValueOf:=0, ByChange:="$X$79:$AD$79", _
            Engine:=3, EngineDesc:="Evolutionary"
        SolverSolve UserFinish:=True ' 后台运行,不弹出求解完成对话框
    Else
        ' --- Solver2 逻辑占位(请替换为你的实际代码)---
        ' 示例模板:
        ' SolverAdd CellRef:="[约束单元格范围]", Relation:=[关系代码], FormulaText:="[约束值]"
        ' SolverOk SetCell:="[目标单元格]", MaxMinVal:=[1=最小化,2=最大化,3=等于], ValueOf:="[目标值]", ByChange:="[可变单元格范围]", _
        '     Engine:=[求解引擎编号], EngineDesc:="[引擎名称]"
        ' SolverSolve UserFinish:=True
        MsgBox "请补充Solver2的VBA代码逻辑"
    End If
    
    ' 可选:保存当前Solver配置到指定单元格
    SolverSave SaveArea:="$A$100"
End Sub

关键细节说明

  • SolverReset:必须在每次求解前调用,清除之前的约束和配置,防止新旧规则冲突
  • UserFinish:=True:添加该参数可实现后台自动求解,无需手动确认求解结果,适合自动化场景
  • 关系代码对应规则:1=小于等于、2=大于等于、3=等于、4=整数约束,与Solver界面设置一一对应

内容的提问来源于stack exchange,提问作者Loren S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 01:47:29