简体   繁体   中英

Goal seek macro, changing cell reference not a hard value

I am trying to make a goal seek macro for my excel model. Is it possible to create a macro that the ChangingCell is not a hard value but an equal formula that refers to a hard value.

Range("D1").GoalSeek Goal:=0.17, ChangingCell:=Range("D424")

So in this case cell D424 would be = to another cell that has a hard value in it. The reason why I can set the ChangingCell directly to D424 is that the goal seek reference for the changing cell changes based on various selections on the file.

You could create a range object for the cell that will be changing by using the DirectPrecedents method on cell D424. This is assuming D424 refers only to one cell.

Sub MyGoalSeek()

Dim precedentRange As Range

Set precedentRange = Range("D424").DirectPrecedents

Range("D1").GoalSeek Goal:=0.17, ChangingCell:=precedentRange

End Sub
Public Function GoalSeek(Goal As Double, ChangingCell As Range) As Double
   Dim changingCellVal As Double

   'Ensure the user only passes in a single cell, not a range of cells
   if(ChangingCell.Rows.Count = 1 And ChangingCell.Columns.Count = 1) Then
       changingCellVal = ChangingCell.Value
   end if

   'Calculate GoalSeek
   GoalSeek = 0
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM