UDF for array formulas created from macro

≡放荡痞女 提交于 2019-12-25 08:31:18

问题


I want to create a udf for a formula I have written on excel. The formula is as follows:

=INDEX('Pivot-LH'!$D$5:$D$1650,SMALL(IF(B93='Pivot-LH'!$A$5:'Pivot-LH'!$A$1650,ROW('Pivot-LH'!$A$5:'Pivot-LH'!$A$1650)-ROW('Pivot-LH'!$A$5)+2),1))

Basically the syntax is to look for cell B93 (variable) through some data on Pivot-LH sheet and return the 1st, 2nd and 3rd values.

I want to define a udf for this and tried to do this by recording a macro. It gave the following result which I modified to enter B93 as a variable called newroute. However this always gives the value zero:

Public Function LH(newroute As Range) As Variant

Selection.FormulaArray = "=INDEX(R5C4:R1650C4,SMALL(IF(newroute=R5C1:R1650C1,ROW(R5C1:R1650C1)-ROW(R5C1)+2),1))"

End Function

Why does it not give the same result as the formula?


回答1:


If you want to call LH from a worksheet formula, your function can only return a value. It cannot update the sheet directly.

See: https://support.microsoft.com/en-us/kb/170787

A user-defined function called by a formula in a worksheet cell cannot change the environment of Microsoft Excel. This means that such a function cannot do any of the following:

  • Insert, delete, or format cells on the spreadsheet.
  • Change another cell's value.
  • Move, rename, delete, or add sheets to a workbook.
  • Change any of the environment options, such as calculation mode or screen views.
  • Add names to a workbook.
  • Set properties or execute most methods.

So you need something like:

Public Function LH(newroute As Range) As Variant

    LH = newroute.Parent.Evaluate("=INDEX(R5C4:R1650C4,SMALL(IF(" & _
                              newroute.Address() & _
            "=R5C1:R1650C1,ROW(R5C1:R1650C1)-ROW(R5C1)+2),1))"

End Function



回答2:


Try this

Public Function LH(newroute As Range) As Variant

Selection.FormulaArray = "=INDEX(R5C4:R1650C4,SMALL(IF(" & newroute.address & "=R5C1:R1650C1,ROW(R5C1:R1650C1)-ROW(R5C1)+2),1))"

End Function


来源:https://stackoverflow.com/questions/39231915/udf-for-array-formulas-created-from-macro

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