【问题标题】:Find indexof Object in ArrayList在 ArrayList 中查找 indexof 对象
【发布时间】:2018-09-18 16:34:49
【问题描述】:

我有一段简单的测试代码:

Sub test()
    Dim testList As Object
    Set testList = CreateObject("System.Collections.ArrayList")
    testList.Add Range("a1")
    Debug.Print testList.IndexOf(Range("a1"))
End Sub

返回错误而不是列表中对象的索引。为什么会这样,如果我没有添加Range,而是添加了自定义myClass,那么myClass Implement 必须如何才能使其正常工作?还是无法在ArrayList 中查找对象?

【问题讨论】:

  • 两个指向同一个单元格的Range 存储在两个不同的对象中。因此,要么在字典/集合中映射地址/范围,要么将完整地址添加到列表中:testList.Add Range("a1").Address(True, True, , true)

标签: vba excel arraylist data-structures


【解决方案1】:

给你:

Option Explicit

Sub TestMe()

    Dim testList As Object
    Set testList = CreateObject("System.Collections.ArrayList")

    Range("A1") = "soready"
    Range("B1") = "tohelp"        

    testList.Add (Range("A1"))
    testList.Add (Range("B1"))

    Debug.Print testList.IndexOf("tohelp", 0)

End Sub

它打印1,这是“tohelp”的正确索引。

【讨论】:

  • 是的,这适用于 Ranges,但对于其他对象呢?我正在将自定义类添加到列表中。我相信你给出的这种方法是有效的,因为Range.Valuedefault member...所以我必须设置我班级的默认成员吗?还是我误解了IndexOf 在内部的工作方式?
  • 所以我必须设置班级的默认成员 - 我会说是的。这就是使用对象进行排序的方式。
猜你喜欢
  • 1970-01-01
  • 2013-10-12
  • 1970-01-01
  • 2011-02-15
  • 1970-01-01
  • 1970-01-01
  • 2018-06-13
  • 2017-05-26
相关资源
最近更新 更多