对于指向同一单元格的两个范围变量,`Is` 运算符不 return 为真

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

我有一个名为 imera 的自定义 class,其中包含一个名为 date_cell.

的范围 属性

创建 imera 的 collection 时,每个 imera 的 date_cell 都设置为引用 excel 中的特定单元格。

尝试在 date_cell 中搜索 collection 时:

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 

"Is" 运算符似乎没有按预期工作并且 return 是正确的,尽管我已经 debug.print 测试过我的收藏中存在一个带有 [=29= 的图像] 设置为范围 ("C27").

因此,上面的“做某事”部分永远不会执行。

是否有任何解释为什么会发生这种情况?

只有在比较对象的相同 实例 时,Is 运算符才会 return 为真。来自 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.

您可以比较 day.date_cell.address 而不是检查相同的范围。

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