乐于分享
好东西不私藏

Excel VBA字典基础概念详解2

Excel VBA字典基础概念详解2

字典与数组、集合的区别–(代码输入)

' 示例:字典、数组、集合对比Sub CompareDataStructures()    ' 准备测试数据    Dim fruits(1 To 3) As String    fruits(1) = "Apple"    fruits(2) = "Banana"    fruits(3) = "Orange"    Dim prices(1 To 3) As Double    prices(1) = 3.5    prices(2) = 2.8    prices(3) = 4.2    ' 1. 使用数组查找(需要遍历)    Dim fruitToFind As String    fruitToFind = "Banana"    Dim i As Long, foundIndex As Long    foundIndex = 0    For i = LBound(fruits) To UBound(fruits)        If fruits(i) = fruitToFind Then            foundIndex = i            Exit For        End If    Next i    If foundIndex > 0 Then        Debug.Print "数组查找 - " & fruitToFind & "的价格: " & prices(foundIndex)    Else        Debug.Print "数组查找 - 未找到" & fruitToFind    End If    ' 2. 使用集合查找(键必须是字符串,值可以是任意对象)    Dim coll As New Collection    On Error Resume Next  ' 忽略重复键错误    coll.Add 3.5, "Apple"    coll.Add 2.8, "Banana"    coll.Add 4.2, "Orange"    On Error GoTo 0    Dim price As Double    On Error Resume Next    price = coll("Banana")    If Err.Number = 0 Then        Debug.Print "集合查找 - Banana的价格: " & price    Else        Debug.Print "集合查找 - 未找到Banana"    End If    On Error GoTo 0    ' 3. 使用字典查找(最直观)    Dim dict As Object    Set dict = CreateObject("Scripting.Dictionary")    dict("Apple") = 3.5    dict("Banana") = 2.8    dict("Orange") = 4.2    If dict.Exists("Banana") Then        Debug.Print "字典查找 - Banana的价格: " & dict("Banana")    Else        Debug.Print "字典查找 - 未找到Banana"    End IfEnd Sub