VBA中的求解器循环问题

问题描述 投票:0回答:1

我对求解器有困难。我试图开发一个for循环,它会多次调用求解器,但我遇到了问题。我已经从工具/参考中添加了求解器的参考到工作簿。我成功地使循环与解算器一起工作;遗憾的是,求解器不会自动更改输入单元格。我觉得这个问题可以通过SolverReset函数解决,但每次我使用它都会失败,并且循环无法再找到解决方案而无需手动重新解决系统问题。我的代码如下。

 Sub Go_Click() 

    'Variable Types
    Dim x As Double 
    Dim First_Variable As Range 
    Dim Second_Variable As Range 
    Dim Number_of_Calculations As Double 
    Dim Input_Cells As Range 
    Dim First_Dimension_Lower As Double 
    Dim y As Double 

    Number_of_Calculations = 6 

    x = (First_Dimension_Upper_Bound - First_Dimension_Lower_Bound) /  Number_of_Calculations 

    For y = 1 To Number_of_Calculations 

         ' x is the integer that the first dimension of the solve will increase by.
         ' by finding the difference between the upper and lower bound and dividing by the number of calculations
         ' then the rest is just a for loop, adding the value "x" to each loop

        SolverOk SetCell:="First_Dimension", _ 
        MaxMinVal:=3, _ 
        ValueOf:=First_Dimension_Lower_Bound, _ 
        ByChange:="Input_Cells", _ 
        Engine:=1, EngineDesc:="GRG Nonlinear" 
        SolverSolve 

         'Just to test the results
         MsgBox (Range("b4")) 

         'increase in the lower first dimension bound
         First_Dimension_Lower_Bound = First_Dimension_Lower_Bound + x 

     Next y 

 End Sub 
excel vba loops excel-vba for-loop
1个回答
0
投票

检查SolverSolve的返回结果,以发现它是否成功完成:

如果尚未完全定义求解器问题,SolverSolve将返回#N / A错误值。否则,Solver将运行,SolverSolve将返回与“求解器结果”对话框中显示的消息对应的整数值。

链接页面列出了返回的可能整数值。例如,5表示“Solver无法找到可行的解决方案”。

您还可以提供函数名称作为ShowRefSolverSolve参数:

SolverSolve(UserFinish, ShowRef)

如果Solver暂停链接页面中列出的原因之一,则将调用此函数。例如,2表示:

调用的函数是因为超出了“求解器选项”对话框中的“最大时间限制”。

© www.soinside.com 2019 - 2024. All rights reserved.