I would like to create a macro to enable me to select an active cell("Q50") which will generate solver by minimising value in activecell by changing cells $M$2,$M$3,$M$5,$M$7
subject to $M$2>=0 and $M$3>=0
. Every thing with the code works fine for the first selected activecell. However when I click the subsequent cell down the row ("Q51")
, the code doesn't work for the solver anymore. Kindly help. I am a beginner in VBA. See below for code.
Sub JCCMacro()
' JCCMacro Macro
'Save ActiveCell Reference for future use
Dim PrevCell As Range
Set PrevCell = ActiveCell
'Solver Code
SolverOk SetCell:="PrevCell.Select", MaxMinVal:=2, ValueOf:="0", ByChange:= _
"$M$2,$M$3,$M$5,$M$7"
SolverSolve UserFinish:=True
SolverFinish KeepFinal:=1
'Copy in sample and out of sample error
PrevCell.Resize(1, 3).Copy
'Paste Values of in sample and out of sample errors
PrevCell.Offset(0, 4).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'Copy Co-efficient
Range("M2:M7").Select
Application.CutCopyMode = False
Selection.Copy
'Select paste destination
PrevCell.Offset(0, 7).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=True
'Copy Paste Following months data
PrevCell.Offset(1, -1).Resize(12, 1).Copy
'Select target destination
PrevCell.Offset(0, 13).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=True
PrevCell.Offset(1, 0).Select
End Sub
I think you want something like this:
If you want solver to use different variable or constraint cells, you will need to change the cell addresses shown in the code. Or define a
Range
variable which you then change to point to the new cells, using theOffset
method maybe, and in the solver code userangeVariable.Address
instead of$m$2
.