0

I have a VBA user defined function. Besides to assigning a value to the function, I need to assign a value to a cell which is not the cell calling the function. However, when I try to execute the code, it fails: the error #VALUE appears in the cell from which the function is called and in the other cell no value is assigned. Is it a VBA excel limitation or is there a bug in my code? Here is the code sample:

Function zz()
    zz = "OK"
    Row = ActiveCell.Row
    col = ActiveCell.Column
    Cells(Row + 1, col) = "pippi"
End Function

Many thanks.

1
  • UDF's (used in formulas in the worksheet) are not able to modify cell values directly. The following post has some responses giving work-arounds that might be helpful stackoverflow.com/q/12501759/212869 Commented Nov 13, 2022 at 21:32

1 Answer 1

1

Instead of trying to directly update another cell, your UDF can return an array, which can "auto-spill" into an adjacent cell (depending on how you orient your array)

https://www.contextures.com/excelspillformulaexamples.html

For example:

Function zz()
    Dim rv(1 To 2, 1 To 1)
    rv(1, 1) = "OK"
    rv(2, 1) = "pippi"
    zz = rv
End Function

Note: inside a UDF you can use either Application.Caller or Application.ThisCell to refer to the cell containing the formula. If you use ActiveCell there's no guarantee that's going to be the cell you want.

Sign up to request clarification or add additional context in comments.

1 Comment

That is a clever workaround, Many thanks! Anyway I got that vba does not allow to assign a value to a cell from a function directly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.