我使用求解器(帶約束)在 excel 中執行了一些計算,我想在 VBA 中撰寫一個功能完全相同的函式。但是,我有一個問題,在 VBA 中使用求解器。我讀到可以使用求解器,但是您必須參考作業表中的某個單元格,這不是我想要的。我想要的是這樣的:
Function find_maximum(x As Double)
arg_to_bound = x 1 %%% Created variable for constraint
fun_to_maximize = -(x - Exp(x)) %%% Function I want to maximize
%%% Pseudo code %%%
find_maximum = solver(maximize = fun_to_maximize, constraint = arg_to_bound <=1)
End Function
有沒有可能以這種方式擁有它?我在函式內部做所有事情?
uj5u.com熱心網友回復:
您可以以編程方式設定求解器模型并在函式內求解。模型的設定必須在活動作業表上完成,依賴關系以 Excel 公式表示。
Public Function FindMaximum(ByVal x As Double) As Variant
With Worksheets(1)
.Activate
.Range("B1").Formula = "=-(A1 - Exp(A1))"
.Range("A2").Formula = "=A1 1"
SolverReset
SolverAdd "$A$2", 1, "1"
SolverOk "$B$1", 1, , "$A$1"
SolverSolve True
SolverFinish 1
FindMaximum = .Range("B1").Value
End With
End Function
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/490353.html
上一篇:“作業表”物件沒有屬性“單元格”
下一篇:如何將“FirstnameLastnameFirstname2Lastname2”拆分為“FirstnameLastname”“Firstname2Lastname2”?
