名难取一比吊糟 名难取一比吊糟
关注数: 11 粉丝数: 25 发帖数: 651 关注贴吧数: 92
闲来无事,用字典做个简单的map 类模块:StringMap Private istyle As String '数据类型 Private dic As Dictionary '字典 Private const_arr As Variant '基本数据类型 Private flag As Boolean '初始化 Private Sub Class_Initialize() flag = False const_arr = Array("boolean", "byte", "integer", "single", "double", "long", "string", "currency", "date", "variant()") style = "String" Set dic = New Dictionary End Sub '获取map中value的类型 Public Property Get valueStyle() As String valueStyle = istyle End Property '获取所有的key Public Property Get keys() keys = dic.keys End Property '获取所有的item Public Property Get items() items = dic.items End Property '添加数据 Public Sub add(key As String, value As Variant) If flag = False Then istyle = typename(value): flag = True If typename(value) <> istyle Then MsgBox "请确保加入的数据类型一致": Exit Sub If typename(key) <> "String" Then MsgBox "输入的key必须为字符串类型": Exit Sub If Len(Trim(key)) = 0 Then MsgBox "输入的key不能为空": Exit Sub '判断value是不是基本类型 If isSet(getTypeName(value)) Then dic(key) = value Else If dic.Exists(key) Then dic.remove (key) dic.add key, value End If End Sub '获取某个值 Public Function getvalue(key As String) As Variant If (dic.Exists(key)) Then If isSet(getTypeName(dic(key))) Then getvalue = dic(key) Else Set getvalue = dic.Item(key) End If Else MsgBox "map中无对应的值": Exit Function End If End Function '获取StringMap的大小 Public Function size() As Long size = dic.count End Function '移除key Public Sub remove(key As String) If typename(key) = "String" Then If dic.Exists(key) Then dic.remove (key) Exit Sub End If End If MsgBox key & "不存在" End Sub '获取参数类型 Private Function getTypeName(clazz As Variant) As String getTypeName = typename(clazz) End Function '是否需要set操作 Private Function isSet(typename As String) As Boolean For i = 0 To UBound(const_arr) If const_arr(i) = LCase(typename) Then isSet = True Exit Function End If Next i isSet = False End Function 使用: Sub main1() Dim map As StringMap Dim coll As Collection 'Dim d As rng Set coll = New Collection coll.add "nihao a " Set map = New StringMap arr1 = Range("a1:b3") Call map.add("jian1", Range("a1:b3")) brr1 = map.items crr1 = map.keys style = map.valueStyle map.remove ("jian1") Debug.Print map.size Stop End Sub
1 下一页