Rubberduck
Rubberduck copied to clipboard
Funtion/Property non-object return value is used/assigned to as if it is not a temporary copy
A property or function that returns a non-object variable (i.e a value-type, string, UDT type, or a Variant array), is returning a copy of the object's data. There are some justified reasons for working with the copy, but not when you think you're changing the values in the original object.
Some of the examples assign to the copy, and then immediately discard the adjusted copy.
Sub foo()
'Assigning to the return value of Range.Value
Dim rng As Range
Set rng = Sheet1.Range("A1:A4")
rng()(1, 1) = "foo"
rng.Value()(1, 1) = "foo"
'Dictionary with a string in Items
Dim dic As Scripting.Dictionary
Set dic = New Dictionary
dic.Add 1, "FOO"
dic.items(0) = "BAR" '"BAR" is assigned to the copy of the Items array
Debug.Print dic.items(0) 'Prints "FOO"
Dim items As Variant
items = dic.items
items(0) = Replace$(items(0), "O", "E")
Debug.Print dic.items(0) 'Prints "FOO"
Range("A1") = items(0) 'This is a subsequent use of the copy, which is probably justified.
'Dictionary with an Object member in Items
dic.Add 2, Application
Set dic.items(1) = Nothing 'Assigns Nothing to a copy of the Items array
Debug.Print dic.items(1) Is Nothing 'Prints False
Dim c As myClass
Set c = New myClass
c.Name = "FOO"
Replace c.Name, "O", "E"
Debug.Print c.Name 'Prints "FOO"
End Sub
I'm tagging as code-path-analysis, because the inspection would potentially need to see if the copy is assigned to, and then subsequently read from by subsequent code.
refer #2586