Search code examples
vbaexcelreferenceequality

`Is` operator does not return true for two range variables that point to the same cell


I have a custom class named imera in which I include a range property named date_cell.

When creating a collection of imera's, every imera's date_cell is set to reference to a specific cell in excel.

While attempting to search within the collection by date_cell:

Option Explicit
Public imeraCol as Collection
Sub searchByDateCell()
    Dim day As imera
    Dim LastMetrisi As Range
    Set LastMetrisi = Range("C27")
    For Each day In imeraCol
        If day.date_cell Is LastMetrisi Then
            'Do something
        End If
    Next day
    Set day = Nothing
End Sub 

the "Is" operator doesn't seem to work as expected and return true, although I have tested by debug.print that in my colection exists an imera with date_cell set to range("C27").

And as a result the 'Do something section above, never executes.

Is there any explanation why might this happening?


Solution

  • The Is operator will only return true when comparing the same instance of an object. From this MDSN article:

    The Is operator determines if two object references refer to the same object. However, it does not perform value comparisons. If object1 and object2 both refer to the exact same object instance, result is True; if they do not, result is False.

    You could compare day.date_cell.address instead to check for the same range.

    If day.date_cell.Address = LastMetrisi.Address Then
       'Do Something...