How to use goal seek function in Excel user function?

扶醉桌前 提交于 2020-03-04 04:22:51

问题


There is method to use goal seek in MS excel like follows code. It works fine.

   Sub GSeek() 
      With Worksheets("Sheet1") 
             .Range("H18").GoalSeek _  
              Goal:=.Range("H21").Value, _ 
               ChangingCell:=.Range("G18")
     End With 
   End Sub

And I would like to use a function to do the goal seek like follows.

  Function fSeek(a As Range, b As Range, c As Range)
     a.GoalSeek Goal:=b.Value, ChangingCell:=c
     fSeek = "Ok"
   End Function

However, the code work peacefully and no answer was got in the range c. Where am I wrong?


回答1:


I am writing an answer because it seems this question is resurging.

Bottom line is that User-Defined Functions (UDF) are not allowed to change other cells when invoked from a formula.

Solution: To automate godl-seeking, write a VBA macro, not a UDF.

A macro can automate goal-seeking on any range or set of cells. Since a macro does not have parameters, there are many ways to permit the user specify the set of cells to GoalSeek and the parameters, and to route these to the Range.GoalSeek method:

1- Design a dedicated UserForm

2- Use VBA's InputBox function, or possibly Excel's Application.InputBox fuction with parameter type:=8 to enter a range.

3- dedicate some cells on the worksheet where the user can enter the parameters.




回答2:


Thank you all for answering me. I found my question again here after a long time. I happened to find the solution to the this question by using the event.

In the Microsoft Excel Object-Sheet1(Sheet1), we can only write the following code:

 '----------------------------------------------
 ' Goal seeking when the worksheet changes.
 '----------------------------------------------
 ' Here we want to do goal seek for Range("H18") 
 '  with the Goal cell as  Range("H21") 
 '  and  the changing cell as Range("G18").
 '
 Private Sub Worksheet_Change(ByVal Target As Range)
     Range("H18").GoalSeek Goal:=Range("H21"), ChangingCell:=Range("G18")
 End Sub

Is it cool?

Yun



来源:https://stackoverflow.com/questions/45046979/how-to-use-goal-seek-function-in-excel-user-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!