- 帖子
- 4901
- 主題
- 44
- 精華
- 24
- 積分
- 4916
- 點名
- 135
- 作業系統
- Windows 7
- 軟體版本
- Office 20xx
- 閱讀權限
- 150
- 性別
- 男
- 來自
- 台北
- 註冊時間
- 2010-4-30
- 最後登錄
- 2025-6-3
               
|
Dictionary物件可視為一個陣列,讓你放入數字或文字。
那麼它和一般陣列有何不同? Dictionary像一個二維陣列,
裡面每一筆資料包含索引值與資料內容兩個欄位;
於是可以方便的透過Dictionary的Exists函數用來檢查及比對資料,
例如你可用來檢查資料是否重覆。
Dictionary也擁有 Add, Remove, RemoveAll... 等方法,可處理其中的值。
以下的範例建立一個 Dictionary物件:
Dim nums As Object
Set nums = CreateObject("Scripting.Dictionary")
以下的語法把資料加入 Dictionary物件:
dictionary_object.Add index, content
索引值可以是數值或字串。
範例:
nums.Add Cells(1,1), Cells(1,1)
以下的範例檢查指定值是否存在於 Dictionary物件:
If Not nums.Exists(123) Then Msgbox "不存在" Else Msgbox "存在"
可參考這裡以得到Dictionary較完整的認識 --
http://www.officefans.net/cdb/viewthread.php?tid=13039
應用範例
以下都是在其他論壇回答的案例,所以你也許似曾相識..
範例一. 檢查某值是否存在於某數列(類似工作表的 COUNTIF 函數)
Sub check_Num()
Dim nums As Object
Set nums = CreateObject("Scripting.Dictionary")
For Each n In Array(123, 234, 213, 124)
nums.Add n, n
Next
If nums.Exists(222) Then MsgBox "Found!" Else MsgBox "Not Found!"
Set nums = Nothing
End Sub
也可以寫成自訂函數。
範例二. 檢查指定欄的重覆值並予以清除 (保留被清除後的空格)
Sub check_Num()
Dim nums As Object
Set nums = CreateObject("Scripting.Dictionary")
For Each c In Array("A", "C") '處理A欄及C欄
last_row = Cells(65536, c).End(xlUp).Row
For r = last_row To 1 Step -1
Set cell = Cells(r, c)
If Not nums.Exists(cell.Value) Then
nums.Add cell.Value, cell.Value
Else
cell.ClearContents
End If
Next r
nums.RemoveAll '移除Dictionary中的所有資料
Next
Set nums = Nothing
End Sub
範例三. 檢查並剔除指定欄的重覆值 (不保留空格)
Sub check_Num()
Dim nums As Object
Set nums = CreateObject("Scripting.Dictionary")
For Each c In Array("A", "C")
Set cell = Cells(1, c)
While cell <> ""
If Not nums.Exists(cell.Value) Then
nums.Add cell.Value, cell.Value
End If
Set cell = cell.Offset(1, 0)
Wend
Columns(c).ClearContents
r = 1 '從第1列開始再寫回儲存格
For Each num In nums
Cells(r, c) = num
r = r + 1
Next
nums.RemoveAll
Next
Set nums = Nothing
End Sub
註:
範例中的需求並非一定要用Dictionary解決,範例只是範例。
同一個案例可能有多種解法,各有優劣,各憑喜好。
以上說明,如有不足或錯誤之處,敬請指正~
如果你有其他的相關應用,也歡迎分享!
« 最後編輯時間: 2005-04-03, 21:18:05 由 leonchou »
http://gb.twbts.com/index.php?topic=510.0 |
|