Excel VBA字典基础概念详解2
字典与数组、集合的区别–(代码输入)
' 示例:字典、数组、集合对比Sub CompareDataStructures()' 准备测试数据Dim fruits(1 To 3) As Stringfruits(1) = "Apple"fruits(2) = "Banana"fruits(3) = "Orange"Dim prices(1 To 3) As Doubleprices(1) = 3.5prices(2) = 2.8prices(3) = 4.2' 1. 使用数组查找(需要遍历)Dim fruitToFind As StringfruitToFind = "Banana"Dim i As Long, foundIndex As LongfoundIndex = 0For i = LBound(fruits) To UBound(fruits)If fruits(i) = fruitToFind ThenfoundIndex = iExit ForEnd IfNext iIf foundIndex > 0 ThenDebug.Print "数组查找 - " & fruitToFind & "的价格: " & prices(foundIndex)ElseDebug.Print "数组查找 - 未找到" & fruitToFindEnd If' 2. 使用集合查找(键必须是字符串,值可以是任意对象)Dim coll As New CollectionOn Error Resume Next ' 忽略重复键错误coll.Add 3.5, "Apple"coll.Add 2.8, "Banana"coll.Add 4.2, "Orange"On Error GoTo 0Dim price As DoubleOn Error Resume Nextprice = coll("Banana")If Err.Number = 0 ThenDebug.Print "集合查找 - Banana的价格: " & priceElseDebug.Print "集合查找 - 未找到Banana"End IfOn Error GoTo 0' 3. 使用字典查找(最直观)Dim dict As ObjectSet dict = CreateObject("Scripting.Dictionary")dict("Apple") = 3.5dict("Banana") = 2.8dict("Orange") = 4.2If dict.Exists("Banana") ThenDebug.Print "字典查找 - Banana的价格: " & dict("Banana")ElseDebug.Print "字典查找 - 未找到Banana"End IfEnd Sub
夜雨聆风