2013-12-09 38 views
8

我試圖實現使用Excel VB簡單的牛頓法迭代求解器(我從來沒有用過VB)循環離不開錯誤

我不斷收到錯誤loop without a Do,我想不出什麼我」在這裏做錯了。

我試圖找到稱爲壓縮因子的函數z^3 - z^2 - (B^2 + B - A)z - A*B的根源。

我的源MSN

Function zCalculation(ByVal temp As Double, ByVal press As Double) As Double 

Dim tempCr As Double 
Dim pressCr As Double 
Dim A As Double 
Dim B As Double 

tempCr = temp/238.5 

pressCr = press/547.424092 

A = pressCr/tempCr 
A = A/(9 * (2^(1/3) - 1)) 
B = pressCr/tempCr 
B = B * (2^(1/3) - 1)/3 



Dim zNot As Double 
Dim counter As Integer 
counter = 0 
zNot = 1# 

Do 
    counter = counter + 1 

    zNot = zNot - (zNot^3 - zNot^2 - (B^2 + B - A) * zNot - A * B)/(3 * zNot^2 - 2 * zNot - (B^2 + B - A)) 
    If counter > 1000 Then 
     Exit Do 

Loop Until eval(zNot, A, B) < 0.000001 


zCalculation = zNot 


End Function 

休息

Function eval(ByVal z As Double, ByVal A As Double, ByVal B As Double) As Double 

    eval = z^3 - z^2 - (B^2 + B - A) * z - A * B 

End Function 

回答

12

你需要一個:

End If 
在你的代碼

+0

宕.....就是這樣。謝謝!不能相信我錯過了這一點。 –

+3

不是你的錯............在這種情況下,Excel的錯誤信息是不正確的。 –

+1

不能相信我確實在檢查這個之前在stackoverflow上搜索 – Tascalator

1

你可以試試:

Function zCalculation(ByVal temp As Double, ByVal press As Double) As Double 

    Dim tempCr As Double 
    Dim pressCr As Double 
    Dim A As Double 
    Dim B As Double 

    tempCr = temp/238.5 

    pressCr = press/0.546789 

    A = pressCr/tempCr 
    A = A/(9 * (2^(1/3) - 1)) 
    B = pressCr/tempCr 
    B = B * (2^(1/3) - 1)/3 



    Dim zNot As Double 
    Dim counter As Integer 
    counter = 0 
    zNot = 1# 

    Do 
     counter = counter + 1 

     zNot = zNot - (zNot^3 + zNot^2 - (B^2 + B - A) * zNot - A * B)/(3 * zNot^2 + 2 * zNot - (B^2 + B - A)) 
     If counter > 1000 Then 
     Exit Do 
     End if ' <--- Here 

    Loop Until eval(zNot, A, B) < 0.000001 

    zCalculation = zNot 
End Function 
+0

雖然你有它正確以及加里首先發布。謝謝! –

+0

沒問題的人。我很樂意爲您提供幫助。 – Makah

-2
Sub datacalculationsandformat() 
Dim row As Integer 
row = 2 
Do While Cells(row, 2) <> "" 
Cells(row, 3).Value = Cells(row, 2).Value * 0.3 
Cells(row, 4).Value = Cells(row, 2) * 0.1 
Cells(row, 5).Value = Cells(row, 2).Value + Cells(row, 3).Value + Cells(row, 4).Value 
If Cells(row, 5).Value >= 8000 Then 
Worksheets("Sheet1").Cells(row, 5).Font.Bold = True 
row = row + 1 
Loop