[ 初めての方へ | 一覧(最新更新順) | 全文検索 | 過去ログ ]
『CollectionオブジェクトのKey取得について』(Dictionary)
Collectionオブジェクトの指定されたインデックスにあるKeyを参照することは可能ですか?
dim c as new collection
c.add "A", "key01"
c.add "B", "key02"
c.add "C", "key03"
debug.print CollectionKey(c, 2)
'key02が出力みたいな
DictionaryやArrayList使えと思われるかもですが、ふと疑問に思ったのとなるべく参照使わないものを作ってみたくなったので
< 使用 Excel:Office365、使用 OS:Windows10 >
なんか出来なさそうな気がするので、 妥協案としては ItemのCollectionとKeyのCollectionを2個イチで管理するとか...?
Rem [Class1] ------------------------------------------------------------ Option Explicit Private myKeys As Collection, myItems As Collection Public Function Count() As Long Count = myItems.Count End Function Public Sub Add(Item, Optional Key, Optional Before, Optional After) myKeys.Add Key, Key, Before, After myItems.Add Item, Key, Before, After End Sub Public Function Item(Index) Item = myItems.Item(Index) End Function Public Function Key(Index) Key = myKeys.Item(Index) End Function Public Sub Remove(Index) myKeys.Remove Index myItems.Remove Index End Sub Private Sub Class_Initialize() Set myKeys = New Collection Set myItems = New Collection End Sub
Rem [Module1] ----------------------------------------------------------- Sub Test() Dim c As New Class1, i As Long c.Add "A", "Key01" c.Add "B", "Key02", 1 c.Add "C", "Key03", , "Key02" For i = 1 To c.Count Debug.Print c.Key(i), c.Item(i), c.Item(c.Key(i)) Next End Sub
(白茶) 2021/10/08(金) 14:46
ありがとうございます
(Dictionary) 2021/10/08(金) 15:44
白茶さんのコードを参考に、ちょっと作ってみました。
[Class1] ------------------------------------------ Option Explicit Private myCol As Collection Private Items_ As Variant Private Keys_ As Variant Public Function Count() As Long Count = myCol.Count End Function Public Sub Add(Item, Optional Key, Optional Before, Optional After) myCol.Add Array(Item, Key), Key, Before, After End Sub Public Function Item(Index) Item = myCol.Item(Index)(0) End Function Public Function Key(Index) Key = myCol.Item(Index)(1) End Function Public Sub Remove(Index) myCol.Remove Index End Sub Private Sub Class_Initialize() Set myCol = New Collection End Sub Public Function Items() ReDim Items_(1 To myCol.Count) Dim i As Long For i = 1 To myCol.Count Items_(i) = myCol(i)(0) Next Items = Items_ End Function Public Function Keys() ReDim Keys_(1 To myCol.Count) Dim i As Long For i = 1 To myCol.Count Keys_(i) = myCol(i)(1) Next Keys = Keys_ End Function
ついでにItemsとKeysも実装しました。
完全に車輪の再発名ですが。
[Module1] -------------------------------------------------- Sub Test() Dim c As New Class1, i As Long c.Add "A", "Key01" c.Add "B", "Key02", 1 c.Add "C", "Key03", , "Key02" For i = 1 To c.Count Debug.Print c.Key(i), c.Item(i), c.Item(c.Key(i)) Next Dim itm For Each itm In c.Items Debug.Print itm Next Dim ky For Each ky In c.Keys Debug.Print ky Next End Sub
(hatena) 2021/10/09(土) 02:58
[ 一覧(最新更新順) ]
YukiWiki 1.6.7 Copyright (C) 2000,2001 by Hiroshi Yuki.
Modified by kazu.