2012年12月9日日曜日

[ExcelVBA] 省略記法


アドベントカレンダー 9日目

連想配列好きな人は、Dictionaryオブジェクトをガンガン使っているとおもいますが
DictionaryオブジェクトのItemは省略して書くことができますよ。

  1. Option Explicit  
  2.   
  3. Sub SampleCode()  
  4.     Dim DicObj As Object  
  5.     Set DicObj = CreateObject("Scripting.Dictionary")  
  6.   
  7.     DicObj.Add "First", CreateObject("Scripting.Dictionary")  
  8.     DicObj.Item("First").Add "Second", CreateObject("Scripting.Dictionary")  
  9.     DicObj.Item("First").Item("Second").Add "Third", CreateObject("Scripting.Dictionary")  
  10.     DicObj.Item("First").Item("Second").Item("Third").Add "Fourth", CreateObject("Scripting.Dictionary")  
  11.     DicObj.Item("First").Item("Second").Item("Third").Item("Fourth").Add "Fifth""ok"  
  12.       
  13.     Debug.Print DicObj.Item("First").Item("Second").Item("Third").Item("Fourth").Item("Fifth")  
  14.     Set DicObj = Nothing  
  15. End Sub  

これをItemを省略して書くと…
  1. Option Explicit  
  2.   
  3. Sub SampleCode()  
  4.     Dim DicObj As Object  
  5.     Set DicObj = CreateObject("Scripting.Dictionary")  
  6.   
  7.     DicObj.Add "First", CreateObject("Scripting.Dictionary")  
  8.     DicObj("First").Add "Second", CreateObject("Scripting.Dictionary")  
  9.     DicObj("First")("Second").Add "Third", CreateObject("Scripting.Dictionary")  
  10.     DicObj("First")("Second")("Third").Add "Fourth", CreateObject("Scripting.Dictionary")  
  11.     DicObj("First")("Second")("Third")("Fourth").Add "Fifth""ok"  
  12.       
  13.     Debug.Print DicObj("First")("Second")("Third")("Fourth")("Fifth")  
  14.     Set DicObj = Nothing  
  15. End Sub  

見慣れない人には、わかりづらいかもしれませんが、
深い階層になった時横に長くなってみづらいことは
まぁまぁあるんで、そういう時とかのためにも.Itemを省略した
書き方に慣れてしまうのも一つの手なのかもしれませんね。

ちなみに、Collectionの.Itemは省略すると叱られます。

0 件のコメント: