2017-02-26 235 views
0

簡單的問題。我有一個代表公式的字符串。Excel VBA - 以VBA計算

Dim formula As String 
formula = Replace(processFormula(2016, 9000, constants, formulaRow), "##", 9000) 
'formula has the value "(1007,27*((9000 - 8820)/10000)+1400)*((9000 - 8820)/10000)" 

MsgBox (formula) 

'Evaluate(formula) not working sadly 

現在我要評價它裏面VBA並返回結果。我沒有得到評估工作的計算。

processFormula是生成公式的函數,它返回一個String。所以一個字符串被放入替換函數中,用一個數字代替'##'。這裏沒什麼神奇的。關於調試器公式是一個帶有上述值的字符串(它直接從調試器複製)。

有沒有簡單易用的方法?

謝謝,我希望它不是重複的。

+0

什麼是'processFormula'?它有什麼功能嗎?什麼輸出來自'processFormula'? – harun24hr

+0

這是一個返回的字符串。所以我把一個字符串放入Replace。 – sascha10000

+0

您應該用1007,27, – h2so4

回答

1

你應該小數點代替小數逗號

Dim formula As String 
formula = replace(Replace(processFormula(2016, 9000, constants, formulaRow), "##", 9000),",",".") 
'formula has the value "(1007,27*((9000 - 8820)/10000)+1400)*((9000 - 8820)/10000)" 

MsgBox (formula) 

Evaluate(formula) 'should work now ;o) 
+0

嗯,你是對的。 – sascha10000

+0

是的:評估總是期待美國英語公式 –

0

使用以下子。

Sub Calculate() 
Dim x As Double 
    x = ((100 * 20)/30 * 500) 
    Range("A1") = x 
    MsgBox x 
End Sub 
+0

中的點替換逗號正如我所說我有一個字符串。我在我的問題中糾正了它。我認爲即使它是一個forumla,我也不能指定一個字符串來加倍。對? – sascha10000

1

應該沒有問題:

Sub eval() 
    MsgBox Evaluate((100 * 20)/30 * 500) 
End Sub 

enter image description here

其等效電池式相匹配。請注意,這是一樣:

(100*20)/(30*500) 

編輯#1:

這也適用於:

Sub eval2() 
    Dim s As String 
    s = "((100 * 20)/30 * 500)" 
    MsgBox Evaluate(s) 
End Sub 
+0

問題是它是一個字符串。我會在我的描述中更改它 – sascha10000

+0

@ sascha10000請參閱我的**編輯#1 ** –

+0

我會在描述中加入確切的公式。 Iam使用評估,因爲你說。它不工作。 – sascha10000