如何使用Do until或if语句获取非负值?

时间:2019-05-30 22:09:12

标签: excel-vba

我有一个要求解的多项式方程:L ^ 3-4043L-60647 = 0在vba中使用目标搜索。 根据我的计算器,该等式给出3个根:L1 = 70.06,L2,-54.04和L3 = -16.02。但是我只希望我的excel单元格中的L显示第一个正根作为答案。 但是,当我使用vba进行球门搜索时,它只会给我-16.02。我该如何在代码中告知只解决正值?

我已经尝试使用Do直到and if语句。但是,请执行直到语句持续崩溃,并且如果If语句给我错误的值。

Sub GoalSeek()

 'GoalSeek Macro
Dim Length As Double
Dim i As Long
Range("Length") = i

If i > 0 Then

    Application.CutCopyMode = False
    Application.CutCopyMode = False

    Range("GS").GoalSeek Goal:=0.1, ChangingCell:=Range("Length")

Else

End If
End Sub

我尝试使用此if语句。但是我的L或“ Length”仅变为0。我是VBA的非常初学者水平。我不知道我在做什么错。

1 个答案:

答案 0 :(得分:0)

GoalSeek获得最接近起始值的解决方案。

您可以使用以下代码:

Sub GoalSeek()
    Dim i As Double
    'Set the initial value to a very high number
    Range("Result").Value = 9999
    'Ask GoalSeek to get the neares solution to that high value
    Range("Formula").GoalSeek Goal:=0, ChangingCell:=Range("Result")
    If Range("Result").Value > 0 Then 
    'If the value is positive, we need to make sure that it is the first positive solution
        i = -1
        Do
            i = i + 1
            'Set a new inital value. This time, a small one (starting from 0)
            Range("Result").Value = i
            'Ask GoalSeek to get the neares solution to the small initial value
            Range("Formula").GoalSeek Goal:=0, ChangingCell:=Range("Result")
        'If the result is negative, loop (increase the initial value and try again till you find the first positive one
        Loop While Range("Result").Value < 0
    Else 'If the nearest result to the high value is negative, keep it & show a message box.
        MsgBox "No +ve solution found"
    End If
End Sub

在您的示例中,您有三种解决方案70.06,-54.04和-16.02

最接近0的是-16.02,最接近9999的是70.6,最接近-9999的是-54.04

如果解决方案是-5、7和12,该怎么办?

最接近9999的是12,但您想要7,对吗?

因此,我们要求最接近0(-5),然后,我们不断增加初始值,直到最接近的解变为7。

请注意,这是假设您对结果会有所了解。

例如,如果解决方案是-1&1,000,000,则此代码将不起作用,因为-1比1,000,000更接近9999。

在这种情况下,您将需要进一步更改初始高值。

AND 如果将其设置为一个太高的值,该值超出了double数据类型1.79E + 308的限制,甚至设置为使公式的结果超过该值的值,您将得到错误。

相关问题