Putting an Excel UDF into the Worksheet object (as opposed to in a module)

心不动则不痛 提交于 2020-07-16 02:36:25

问题


I suspect the answer is "not possible" - but there is no harm in asking this fine community!

I have a Excel 2013 UDF (User Defined Function) that is unique to a certain worksheet.

Currently, I have this UDF in a "Module" in the containing Workbook. But what I would like to do, is to place the UDF code in the "Worksheet Object" so it is only available to that particular Worksheet.

I have tried, of course, but it is not visible, so I naturally get a #NAME? error. I've tried prefacing the Function with Public (which would defeat the object anyway), but to no avail.

Does anyone know of a particular trick?

Thanks in advance, Nic.


回答1:


Depending on the requirements of your function, you could have a clause that only returns the correct answer on the intended worksheet.

Let's say your function takes a range as an input, i.e.

Function CheckSheet(r As Range)
    If r.Parent.Name = "Intended Sheet Name" Then
        CheckSheet = "The correct value!"
    Else
        CheckSheet = CVErr(xlErrNA)
    EndIf
End Function

EDIT:

the previous version can still be used on another sheet, if the Range it takes as a parameter is on the intended sheet. It can be modified to:

Function CheckSheet()
    If Application.Caller.Parent.Name = "Intended Sheet Name" Then
        CheckSheet = "The correct value!"
    Else
        CheckSheet = CVErr(xlErrNA)
    EndIf
End Function

Where Application.Caller returns the cell containing the function.




回答2:


It's not possible. UDFs have to be in a normal module. :)



来源:https://stackoverflow.com/questions/25931008/putting-an-excel-udf-into-the-worksheet-object-as-opposed-to-in-a-module

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