简体   繁体   中英

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).

在此处输入图片说明

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.

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.

You may try the following approach:

Define new named range call it for example SeekCell and in Refers To enter:

=INDEX($I$25:$K$25,1,MATCH("2015"&$C$6,$I$9:$K$9))

Define new named range call it for example ChangeCell and in Refers To enter:

=INDEX($I$10:$K$10,1,MATCH("2015"&$C$6,$I$9:$K$9))

Define new named range call it for example GoalCell and in Refers To enter:

=$C$25

In the VBA code use:

Range("SeekCell").GOALSEEK  Goal:=Range("GoalCell"), ChangingCell:=Range("ChangeCell")

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