Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a cell value from a function

Tags:

excel

vba

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
like image 320
Chris Seymour Avatar asked Mar 27 '13 13:03

Chris Seymour


People also ask

How do you assign a value to a cell in Excel?

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.

How do I return a cell value instead of formula?

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.

How do you set the value of a cell in Excel?

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.

How do you set multiple values at once in Excel?

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

Can I use a function to change the value of another cell?

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.

How do I set a cell value equal to another cell value?

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


1 Answers

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

like image 99
Kazimierz Jawor Avatar answered Oct 03 '22 01:10

Kazimierz Jawor