Share via

"This cell" in a function for Excel

Anonymous
2018-01-18T02:29:06+00:00

When I write a function (myfunc) in VBA for Excel and attach it to a cell through making =myfunc the value of the cell, I need to get information about the cell when the function is executed. VBA is sort of objected-oriented and the OO languages that I know have operators like This or Self. I haven't discovered any such thing for VBA for Excel.

Microsoft 365 and Office | Excel | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

Anonymous
2018-01-18T04:13:49+00:00

Please try this:

Function UseThisCell(r As Range)

UseThisCell = r.Address

End Function

The above function will return the selected cell address.

Was this answer helpful?

0 comments No comments

Answer accepted by question author

OssieMac 48,001 Reputation points Volunteer Moderator
2018-01-18T03:50:17+00:00

I am not sure that I am on the same wavelength as yourself but the following might help.

You can't make =myfunc the value of the cell because as soon as you enter =myfunct in the cell then any previous value in the cell is gone and replaced with the formula = myfunct()

To return information about the cell containing the function then the code below is an example of returning some information about the cell as per the screen shot.

AFAIK the UDF cannot be used to set or change formats in the cell.

To display as above:

  • Set the interior color
  • Set the Font color
  • Turn on Wrap Text
  • Enter the formula in the cell   =MyFunct()

Function MyFunct() As String

    Dim varCaller As Variant

    Dim rngCaller As Range

    varCaller = Application.Caller.Address

    Set rngCaller = Range(varCaller)

    rngCaller.WrapText = True     'This does not do anything. Cannot set formats from the UDF

    MyFunct = rngCaller.Address & vbLf & _

                rngCaller.Interior.Color & vbLf & _

                rngCaller.Font.Color & vbLf & _

                rngCaller.Font.Name

End Function

You could omit the variable varCaller plus the line assigning the Application.Caller.Address to it and use the following line to directly assign Application.Caller to rngCaller.

Set rngCaller = Range(Application.Caller.Address)

If not the answer you are looking for then I need more information. Please provide examples of the formula you want to use in the cell and examples of what you expect to be returned.

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful