Can an Excel VBA UDF called from the worksheet ever be passed an instance of any Excel VBA object model class other than 'Range'?

若如初见. 提交于 2019-12-24 02:16:30

问题


I'm 99% sure that the answer is "no", but I'm wondering if someone who is 100% sure can say so.

Consider a VBA UDF:

Public Function f(x)

End Function

When you call this from the worksheet, 'x' will be a number, string, boolean, error, array, or object of type 'Range'. Can it ever be, say, an instance of 'Chart', 'ListObject', or any other Excel-VBA object model class?

(The question arose from me moving to Excel 2007 and playing with Tables, and wondering if I could write UDFs that accept them as parameters instead of Range. The answer to that seems to be no, but then I realized I didn't know for sure in general.)


回答1:


Your suspicions are correct - you can only pass in limited object types. For example, if I have table on the active worksheet and wanted to know it's column count, I could create a UDF called TableColumnCount and pass in the table name into a function like:

Function TableColumnCount(tn As String) As Integer
    Dim myTableName As ListObject
    Dim ActiveS As Worksheet
    Set ActiveS = ActiveWorkbook.ActiveSheet
    Set myTableName = ActiveS.ListObjects(tn)
    TableColumnCount = myTableName.Range.Columns.Count
End Function

and then call it on sheet with the name of my able as a string, like =TableColumnCount("Table1").

Or as a range object like:

Function TableColumnCount(tn As Range) As Integer
    TableColumnCount = tn.Columns.Count
End Function

And then call it like: =TableColumnCount(Table1)



来源:https://stackoverflow.com/questions/2596296/can-an-excel-vba-udf-called-from-the-worksheet-ever-be-passed-an-instance-of-any

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