簡體   English   中英

如何使用Do until或if語句獲得非負值?

[英]How to get non-negative value using Do until or if statement?

我有一個我想解決的多項式方程:L ^ 3-4043L-60647 = 0在vba中使用目標搜索。 根據我的計算器,該等式給出3個根:L1 = 70.06,L2,-54.04和L3 = -16.02。 但我只希望我的Excel中的L能夠顯示第一個正根作為我的答案。 但是當我使用vba進行goalseek時,它只給了我-16.02。 我怎么在我的代碼中說出只能解決正值?

我已經嘗試過使用Do until和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或“長度”僅為0.我在VBA中非常非常初級。 我不知道我做錯了什么。

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。

在這種情況下,您需要更多地更改初始高值。

如果你將其設置為超過雙倍數據類型為1.79E + 308,甚至到使公式的結果超過它的值的上限設定過高,你會得到一個錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM