vb collection 如何提取key 值出来啊?在线等
为什么vb 的 collection 只能取出 value 值 , 不能取出key 值啊, 这样很不方便 , vb 有什么集合可以这样做啊?
[解决办法]
试了下,可以自己写个函数:
Function Contains(ByVal c As Collection, ByVal sKey As String) As Boolean
On Error GoTo err_c
Dim v
v = c.Item(sKey)
Contains = True
Exit Function
err_c:
If Err.Number = 5 Then Contains = False
'不存在返回False
End Function
再这样处理:
if not Contains(col, CStr(listview .listitem(1).subitems(5))) then
listview添加数据
end if
试试吧,可能不是最好的方法,但应该可以实现吧?
看看楼下还有什么好方法
[解决办法]
可以自己写一个类来替换collection
下面这段代码只是随性写的,可能还存在部分考虑不完善的地方,看看有没有人进一步补充完善
创建一个类模块,命名为MyCollection
代码如下:
Option Explicit
Private colKey As New Collection
Private colVal As New Collection
Public Property Get Count() As Long
Count = colKey.Count
End Property
Public Property Get RealCol() As Collection
Set RealCol = colVal
End Property
Public Sub Add(Item, Optional Key, Optional Before, Optional After)
colKey.Add Key, Key, Before, After
colVal.Add Item, Key, Before, After
End Sub
Public Sub Remove(index)
colKey.Remove index
colVal.Remove index
End Sub
Public Function getKey(index) As String
getKey = colKey.Item(index)
End Function
下面我们用一些代码来测试一下collection特性是否保留,并且我们能不能通过索引号获得key
建个窗体,放个按钮
Private Sub Command1_Click()
Dim a As New MyCollection '创建实例
'加入对象
a.Add "test1 ", "key1 "
a.Add "test2 ", "key2 "
a.Add "test3 ", "key3 "
a.Add "test4 ", "key4 "
a.Add "test5 ", "key5 "
Debug.Print "用索引号方式获取对象 "
Debug.Print a.RealCol(2)
Debug.Print "用key获取对象 "
Debug.Print a.RealCol( "key3 ")
Debug.Print "remove对象 "
a.Remove "key2 "
Debug.Print "for each访问 "
Dim b
For Each b In a.RealCol
Debug.Print b
Next
Debug.Print "罗列所有key "
Dim i As Integer
For i = 1 To a.Count
Debug.Print a.getKey(i)
Next
Debug.Print "异常测试 "
a.Add "asdad ", "key5 " '重复key
a.Remove "key6 " '删除不存在的对象
a.getKey 8 '获取不存在的key
End Sub