When writing MS Excel VBA code I met a simple question, like this.
The upper one has no problem at all.
The lower one has a problem. It gave me "False".
Dim my01, my02
Set my01 = Sheets(1)
Set my02 = Sheets(1)
MsgBox my01 Is my02
Set my01 = Sheets(1).Range("A1")
Set my02 = Sheets(1).Range("A1")
MsgBox my01 Is my02
I expected that it shows "True".
[EDIT] I have tried "=" operator and found that it works well. Though, it does not give any light into my question.
See here:
The
Rangeproperty always returns a new object reference even if you are referring to the same cell. (well, it will re-use previous references if they are not currently pointed to by a variable) - Rory, Feb 12, 2015 at 17:01
This can easily be verified using ObjPtr:
Dim my01, my02
Set my01 = Sheets(1)
Set my02 = Sheets(1)
Debug.Print ObjPtr(my01), ObjPtr(my02) ' Identical, e.g. 1134792280 1134792280
Debug.Print my01 Is my02 ' True
Set my01 = Sheet1.Range("A1")
Set my02 = Sheet1.Range("A1")
Debug.Print ObjPtr(my01), ObjPtr(my02) ' Different!, e.g. 1091015848 1091023048
Debug.Print my01 Is my02 ' False
The linked thread proposes comparing their .Address. You could take it one step further and also compare their .Parent or .Worksheet.
Debug.Print my01.Worksheet Is my02.Worksheet And my01.Address = my02.Address ' True
Short cut solution by using the external-parameter
Debug.print my01.Address(external:=True) = my02.Address(external:=True)
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