title: Excel Solver - constraint with variable range of cells
body: <p>I'm doing a macro in Excel that solves an exercise in Solver. My problem is that the number of variables that form the constraints are variable.
  That is, I have in the sheet "Results" my target cell and my cells to vary. The number of cells to be varied is variable, starting in cell AF22 and ending in cell AF &amp; var11. Similarly, the row of the target cell can also be variable, being in column AH and row var2.
  The restrictions are that cells AG22: AG &amp; var11 are the same as other cells in the sheet "Input data": F31: F &amp; var2.
  When I run the macro I get the error: "Error in the model, check that all the cells and constraints are valid."
  I put the macro so that it is better understood:</p>
  
  <pre><code>var2 = WorksheetFunction.Sum(Val(30), Sheets("Input data").Range("G28").Value)
  var11 = WorksheetFunction.Sum(Val(21), Sheets("Input data").Range("G28").Value)
  var12 = var11 + Val(4)
  '
  'SOLVER
  Sheets("Results").Select
  Range(Cells(22, 32), Cells(var11, 32)).Select
  Selection.ClearContents
  'Objetivo
  SolverReset
  SolverOk SetCell:=Sheets("Results").Cells(var12, 34), MaxMinVal:=2, ValueOf:=0, ByChange:=Sheets("Results").Range(Sheets("Results").Cells(22, 32), Sheets("Resultados válvula").Cells(var11, 32)), Engine:=1, EngineDesc:="GRG NonLinear"
  
  'Constraints
  Set rang = Sheets("Results").Range(Sheets("Results").Cells(22, 33), Sheets("Results").Cells(var11, 33))
  Set const = Sheets("Input data").Range(Sheets("Input data").Cells(31, 6), Sheets("Input data").Cells(var2, 6))
      SolverAdd CellRef:=rang.Address, Relation:=2, FormulaText:=const.Address
  SolverSolve
  </code></pre>
  
  <p>Can anyone help me?</p>
  
  <p>Thank you!</p>