Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Is" operator gives me False, Can I know the reason, why? [duplicate]

Tags:

excel

vba

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.

like image 618
오바마 Avatar asked Oct 25 '25 16:10

오바마


1 Answers

See here:

The Range property 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)
like image 95
5 revs, 2 users 90%BigBen Avatar answered Oct 27 '25 07:10

5 revs, 2 users 90%BigBen