Question : Excel VBA custom function

I tested a custom function and got #VALUE!
Function Macro1(r As range)
r.Cells(2, 2) = "222"
End Function
Why I cannot assign value to a cell?

Answer : Excel VBA custom function

A UDF or User Defined Function is a custom function written in VBA that accepts parameters and returns a value, just like any built in Excel function. A UDF can also return an array of values if it is used in a multiple cell array formula. But a UDF has a very strict limitation: it cannot, under any circumstances, change the structure of the workbook or worksheet, set any workbook or worksheet property such as a cell's value, color, border, or any other worksheet or cell formatting, or change the Excel environment including changing the cursor. This very strict rule also applies to any sub-routine that the UDF calls. If this rule is violated Excel stops the UDF and returns the #VALUE! error to the formula in which the UDF was called.

In addition to the above limitations, the Find, SpecialCells, CurrentRegion, CurrentArray, GoTo, Precedents, and Dependents methods do not function properly when used in a UDF (Find does work in Excel 2002 and later).

Three are a few exceptions to this rule. A UDF or any subroutine called from the UDF can merge and unmerge cells (Merge and UnMerge), indent and outdent (InsertIndent), add, modify, and delete shapes, add, change, and delete cell validation rules, and add, change, and delete cell comments. With regard to shapes, it cannot set or manipulate the Characters object of a TextFrame.

As long as this rule is followed a UDF can read any application, workbook, worksheet, or cell property, define variables, arrays, and collections, process information, display message boxes, and read information from a closed workbook (using an ADODB connection, not ExecuteExcel4Macro as that is also prohibited in a UDF).

Kevin
Random Solutions  
 
programming4us programming4us