I want to set value for cells by VBA. I have googled, and see some resolution:
Sheets("SheetName").Range("A1").value = someValue
Sheets("SheetName").Cells(1,1).value = someValue
With this kind of code, I can just read data from cell A1 but I cannot set a new value to it.
Update
The code to set cell A1 value is put within a Function
as below.
Function abb()
Sheets("SheetName").Range("A1").value = 122333
abb = 'any thing'
End Function
In cell B2, I set =abb()
and hit enter. I get #VALUE but nothing happen at A1.
Putting this code in a macro, it works.
My question is, how to make A1 have values within a function?
it should work - try this
Sheets("Sheet1").Range("A1").Value2 = "value"
you can use both
.Value
and.Value2
, make sure that the sheet name is correct.If you want to modify two cells with one formula, you may want to consider returning an array from your function. Here's an example:
Select cells A2 to B2. Type
=abb()
and press ShiftCtrlEnter to specify that it is an array formula. This formula then modifies both cells (A2 and B2) at the same time.Perhaps you can customise this to do what you want.
From your comment above you wanted to try this approach
If you enter
=abb()
into any cell
Then cell A1 of that sheet wil be set to 12333
This is the line to update to pick the cell to update, and to place a value in it
Range("A1").Value = 122333
From I don't want my Excel Add-In to return an array (instead I need a UDF to change other cells)
You cannot change cell A1 with a function in B2.
Visit: Description of limitations of custom functions in Excel . The text includes:
"A user-defined function called by a formula in a worksheet cell cannot change the environment of Microsoft Excel. This means that such a function cannot do any of the following:
Why do you want to change cell A1 in this way? Explain your objective and perhaps someone can help.