I have a function in a module. The function is defined as follows:
Public Function CourseSetup(ByVal SROfferId As Integer) as string
When the function called, The following line fails:
Worksheets("CourseEvaluation").Range("CourseName").value = "1234"
fails with error 1004.
The same line in a sub (macro) works.
CourseName is a one cell named ranged. Getting the value for the above range works.
In the immediate window:
returns the current value in the range.
Functions called from the worksheet cannot manipulate worksheet objects other than the active cell wherein the formula is entered.
This preserves dependencies in formulae, prevents circular reference errors, etc.
As a general rule, use Subroutines to manipulate objects, and use Formulae to return values (whether to a cell reference or to a variable).
One exception is that a UDF called from within a subroutine can manipulate worksheet objects, but this is probably not a good habit to start. Keep your functions limited to returning values to variables/cells, and use subroutines to manipulate objects.
user defined functions called from cells can only return values to the cell(s) they are called from. So your UDF is not allowed to write values to a defined name.
I ran into this problem a few days ago and found this answer. converting to a sub from a function solved the problem. However, if I called the function in the immediate window, it performed as desired. thought that was odd.