zoukankan      html  css  js  c++  java
  • VBA中Dictionary对象使用(Key,Value)

    Dim dict
    
    ' 创建Dictionary
    Set dict = CreateObject("Scripting.Dictionary")
    
    ' 增加项目
    dict.Add "A", 300
    dict.Add "B", 400
    dict.Add "C", 500
    
    ' 统计项目数
    n = dict.Count
    
    ' 删除项目
    dict.Remove ("A")
    
    ' 判断字典中是否包含关键字
    dict.exists ("B")
    
    ' 取关键字对应的值,注意在使用前需要判断是否存在key,否则dict中会多出一条记录
    Value = dict.Item("B")
    
    ' 修改关键字对应的值,如不存在则创建新的项目
    dict.Item("B") = 1000
    dict.Item("D") = 800
    
    ' 对字典进行循环
    k = dict.keys
    v = dict.Items
    For i = 0 To dict.Count - 1
    key = k(i)
    Value = v(i)
    MsgBox key & Value
    Next
    
    ' 删除所有项目
    
    dict.Removeall
    
    实例:
    
    Sub 宏1()
    
    Set dic = CreateObject("Scripting.Dictionary") '字典
    For i = 1 To 10000
    If Not i Like "*4*" Then
    dic.Add i, "" '如果不包含“1”
    End If
    Next
    Range("a2").Resize(dic.Count, 1) = Application.WorksheetFunction.Transpose(dic.keys) '从A2单元开始向下放置
    End Sub
    View Code
  • 相关阅读:
    笔记-归并排序
    Repeated Substring Pattern
    Assign Cookies
    Number of Boomerangs
    Paint Fence
    Path Sum III
    Valid Word Square
    Sum of Two Integers
    Find All Numbers Disappeared in an Array
    First Unique Character in a String
  • 原文地址:https://www.cnblogs.com/smart9595/p/5179328.html
Copyright © 2011-2022 走看看