The contents of cell A1
is =test(2)
where test
is the function:
Function test(ByRef x As Double) As Double
Range("A2") = x
test = x * x
End Function
Can you explain why this gives #VALUE!
in cell A1
and nothing in cell A2
? I expected A2
to contain 2
and A1
to contain 4
. Without the line Range("A2") = x
the function works as expected (squaring the value of a cell).
What is really confusing is if you wrap test
with the subroutine calltest
then it works:
Sub calltest()
t = test(2)
Range("A1") = t
End Sub
Function test(ByRef x As Double) As Double
Range("A2") = x
test = x * x
End Function
But this doesn't
Function test(ByRef x As Double) As Double
Range("A2") = x
End Function
Click the cell in which you want to enter the formula. , type = (equal sign) and the formula you want to use. Click the tab for the worksheet to be referenced. Select the cell or range of cells to be referenced.
Select the cell with the formula, press F2, and then press ENTER. The cell displays the value. In the same cell, click Cells on the Format menu.
The value property can be used in both ways (you can read and write a value from a cell). You can refer to a cell using Cells and Range Object to set a cell value (to Get and Change also). To set a cell value, you need to use the “Value” property, and then you need to define the value that you want to set.
Set Multiple Cells’ Values at Once Instead of referencing a single cell, you can reference a range of cells and change all of the cell values at once: Range ("A2:A5").Value = 1 Set Cell Value – Text
Excel VBA will not allow a user-defined function to alter the value of another cell. The only thing a UDF is allowed to do (with a few minor exceptions) is to return values to the cells it is called from.
It’s easy to set a cell value equal to another cell value (or “Copy” a cell value): Range ("A1").Value = Range ("B1").Value You can even do this with ranges of cells (the ranges must be the same size): Range ("A1:A5").Value = Range ("B1:B5").Value
Due to Function
fundamentals which state that you can not change or set sheet cells. You need to delete the row with Range("A2") = x
EDIT Some additional link (which I believe is always useful to provide for those who want to analyse UDF topic): Creating custom functions by Microsoft
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With