Excel cell from which a Function is called [duplicate]

荒凉一梦 提交于 2019-11-26 13:05:10

问题


This question already has an answer here:

  • How to get address of cell which calls a VBA Functions in a Excel sheet 1 answer

How can I get the cell where my VBA Function is called from?

In other words, what is the VBA equivalent for INDIRECT(ROW(), COLUMN()) ?

I\'m not looking for ActiveCell.

What I want to do is have a simple function ThisRow_Col(rColumn As String) return the column X of the row it\'s called from. Say in B2 I call =ThisRow_Col(\"A\"), it should return the value of A2. This should work regardless of which cell active.

EDIT: Thanks Charles for the answer: Application.Caller. The following code gets the column X of the current row, independent of where the selection is:

Function ThisRow_Col(rColumn As Range)
    \' Return INDIRECT(rcolumn & ROW())

    ThisRow_Col = Application.Caller.Worksheet.Cells(Application.Caller.Row, rColumn.Column).Value

End Function

Note that passing the column as a Range (ThisRow_Col(A1)) is better than passing it as a string, because Excel can automatically update the formulas if you move or insert columns. Of course the 1 row of A1 is just a convention.


回答1:


Application.Caller returns the range object that the UDF is called from.



来源:https://stackoverflow.com/questions/5559279/excel-cell-from-which-a-function-is-called

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