Search code examples
vbaexcelexcel-2011

Goal Seek Macro with moving Goal and Seek variables


I have a Goal Seek Macro:

Sub GOALSEEK()
    Range("K25").GOALSEEK Goal:=0, ChangingCell:=Range("K10")
End Sub

That works for 2015Q4, cell K25 at 0%.

I want to adapt the macro for moving Goal and Seek variables.

The moving Goal will be stored in C25 (0, 0.01, 0.05, etc), and the moving Seek will be dependent on C6 (Q2, Q3, Q4, which will map to I25, J25, K25, respectively).

enter image description here

EDIT

After some tinkering, I just discovered that the moving Goal can be implemented by changing Goal:=0 to Goal:=Range("Cell"):

Sub GOALSEEK()
    Range("K25").GOALSEEK Goal:=Range("C25"), ChangingCell:=Range("K10")
End Sub

Still don't know how to make Seek move.


Solution

  • Put some conditional logic in your code like below to make the decision on the fly based on which quarter is entered in cell C6.

    Sub GOALSEEK()
    
    Dim gseek, chngcell as Range
    
    If Range("C6") = "Q2" Then
       Set gseek = Range("I25")
       Set chngcell = Range("I10")
    Elseif Range("C6") = "Q3" Then
       Set gseek = Range("J25")
       Set chngcell = Range("J10")
    Elseif Range("C6") = "Q4" Then
       Set gseek = Range("K25")
       Set chngcell = Range("K10")
    End If
    
    gseek.GOALSEEK Goal:=Range("C25"), ChangingCell:=chngcell
    
    End Sub
    

    You could further this to set another range variable to the cell you want to change as well. Let me know if this doesn't work for you.