简体   繁体   English

具有移动目标和搜索变量的目标搜索宏

[英]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%. 这适用于2015年第4季度,单元格K25为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). 移动目标将存储在C25C25等),移动“搜索”将取决于C6 (Q2,Q3,Q4,分别映射到I25,J25,K25)。

在此处输入图片说明

EDIT 编辑

After some tinkering, I just discovered that the moving Goal can be implemented by changing Goal:=0 to Goal:=Range("Cell") : 经过一番修补,我才发现可以通过将Goal:=0更改为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. 仍然不知道如何使Seek移动。

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. 在您的代码中放置一些条件逻辑,如下所示,根据在单元格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: 定义一个新的命名范围,例如SeekCell并在Refers中输入以下内容:

=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: 定义一个新的命名范围,例如ChangeCell并在“引用”中输入:

=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: 定义一个新的命名范围,例如GoalCell并在“引用”中输入以下名称:

=$C$25

In the VBA code use: 在VBA代码中使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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