昱得資訊工作室
麻辣學園
歡迎光臨, 訪客. 請先 登入註冊一個帳號.
您忘了 啟用您的帳號嗎?
2008-09-08, 19:36:39
首頁 說明 登入 註冊 贊助論壇 想當作者?
新聞: 為增進論壇品質,全面更新硬體設備,經費有限,請各位踴躍贊助論壇!!


+  麻辣家族討論區
|-+  MS Office 系列
| |-+  EXCEL
| | |-+  Excel程式區 (版主: hsieh)
| | | |-+  Dictionary物件的認識與應用
0 會員 以及 1 訪客 正在閱讀本篇主題. « 上一篇主題 下一篇主題 »
頁: [1] 向下 列印
作者 主題: Dictionary物件的認識與應用  (閱讀 1569 次)
leonchou
論壇維護群
*
離線 離線

文章: 1160


Dictionary物件的認識與應用
« 於: 2005-04-03, 02:10:45 »

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

應用範例
以下都是在其他論壇回答的案例,所以你也許似曾相識.. Wink

範例一. 檢查某值是否存在於某數列(類似工作表的 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解決,範例只是範例。
同一個案例可能有多種解法,各有優劣,各憑喜好。 Wink

以上說明,如有不足或錯誤之處,敬請指正~
如果你有其他的相關應用,也歡迎分享! Cheesy
« 最後編輯時間: 2005-04-03, 21:18:05 由 leonchou » 已記錄

xxlandbank
中學生
*
離線 離線

文章: 28


Re: Dictionary物件的認識與應用
« 回覆文章 #1 於: 2005-04-03, 10:21:39 »

版大您好:
1.在 nums.Add n, n 中,第二個n是"資料內容",我放入其它值都查不到,可見得只能針對"索引值"做查詢,對否?
2.若此,利用For each dat in nums,也只能找到"索引值",要怎樣才能利用得到"資料內容"(例如:取得.查詢...)呢?
« 最後編輯時間: 2005-04-03, 14:04:32 由 xxlandbank » 已記錄
xxlandbank
中學生
*
離線 離線

文章: 28


Re: Dictionary物件的認識與應用
« 回覆文章 #2 於: 2005-04-03, 10:24:28 »

啊!對不起,我找到答案了,可是又刪除不掉,當灌水好了:
索引值就是keys
資料內容就是items
已記錄
頁: [1] 向上 列印 
« 上一篇主題 下一篇主題 »
跳到:  


本頁花了 0.261 秒, 以及 20 次的資料庫查詢.