'Wha is setting a cell to a value not working?

This must be a very stupid problem, but I just cannot set a value into a cell. I have a very complex VBA file where I try to do that without success, so I simplified my test to a basic empty sheet that contains just one function:

Function test()
   Set Worksheets("Sheet1").Range("A1").Value = 3.1415
End Function

a code copy/pasted from an example here: https://docs.microsoft.com/en-us/office/vba/api/excel.range.value

It doesn't work. Cell A1 stays blank.

Can anyone see the elephant I am missing?



Solution 1:[1]

The Set keyword assigns an object reference to a variable – for example, a reference to a worksheet:

Dim sheet As Worksheet
Set sheet = Worksheets("Sheet1")

3.1415 is a primitive value, not an object reference, so you'd do the assignment without Set:

Worksheets("Sheet1").Range("A1").Value = 3.1415

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jsheeran