Created
September 17, 2014 13:52
-
-
Save CloudCray/e6817a8a3476c171e5ec to your computer and use it in GitHub Desktop.
Solve a cell by changing another cell using Solver in VBA
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'' First, you have to open the Visual Basic for Applications editor | |
'' Tools > References > Check "Solver" (near the top) | |
'' Setup here: http://imgur.com/UZPmZQQ | |
Sub MyMacro() | |
'' x is going to store your target value, which currently sits in cell C5 | |
Dim x As Integer | |
x = Range("$C$5").Value | |
'' If you're on a different Excel, this might all be ".xla" instead of ".xlam" | |
'' You gotta make sure Solver is reset. | |
Application.Run "Solver.xlam!SolverReset" | |
'' Run solver's "SolverOk" function. This takes: | |
'' SovlerOk([SetCell], [MaxMinVal], [ValueOf], [ByChange], [Engine], [EngineDesc]) | |
'' [SetCell] - target cell which you're solving for. In this case, C4. | |
'' [MaxMinVal] - 1=Max, 2=Min, 3=Set to a value. Typically, use 3. | |
'' [ValueOf] - target value of [SetCell]. In this case, we're using x | |
'' [ByChage] - which cell changes their value. In this case, C3 | |
'' [Engine] - no idea | |
'' [EngineDesc] - still no idea | |
Application.Run "Solver.xlam!SolverOk", "$C$4", 3, x, "$C$3", 1, "GRG Nonlinear" | |
'' This variable will store the result type. Stolen from http://peltiertech.com/Excel/SolverVBA.html | |
' Result = 0, Solution found, optimality and constraints satisfied | |
' Result = 1, Converged, constraints satisfied | |
' Result = 2, Cannot improve, constraints satisfied | |
' Result = 3, Stopped at maximum iterations | |
' Result = 4, Solver did not converge | |
' Result = 5, No feasible solution | |
Result = Application.Run("Solver.xlam!SolverSolve", True) | |
Application.Run "Solver.xlam!SolverFinish" | |
End Sub |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment