Skip to content

Instantly share code, notes, and snippets.

@KotorinChunChun
Last active March 4, 2021 16:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KotorinChunChun/be5f5f66bdc21cb53f386c4a44f6689a to your computer and use it in GitHub Desktop.
Save KotorinChunChun/be5f5f66bdc21cb53f386c4a44f6689a to your computer and use it in GitHub Desktop.
VBAのDictionaryの要素の配列には値を代入できない教訓
'二次元配列の列をDictionaryへ、行をArray要素へ変換
Function ToDictionaryArrayByArray2D_NG(data) As Dictionary
Dim dic As New Dictionary
Dim i As Long, j As Long
For j = 1 To UBound(data, 2)
Dim arr
ReDim arr(1 To UBound(data, 1) - 1)
dic(data(1, j)) = arr
Next
For i = 2 To UBound(data, 1)
For j = 1 To UBound(data, 2)
Dim dKey: dKey = data(1, j)
dic.Item(dKey)(i - 1) = data(i, j)
'↑なぜかココで代入できてるのにEmptyから変わらない
Next
Next
If dic.Exists(Empty) Then Call dic.Remove(Empty)
Set ToDictionaryArrayByArray2D_NG = dic
End Function
Function ToDictionaryArrayByArray2D_OK(data) As Dictionary
Dim dic As New Dictionary
Dim i As Long, j As Long
For j = 1 To UBound(data, 2)
Dim arr
ReDim arr(1 To UBound(data, 1) - 1)
Dim dKey: dKey = data(1, j)
For i = 2 To UBound(data, 1)
arr(i - 1) = data(i, j)
Next
dic(dKey) = arr
Next
If dic.Exists(Empty) Then Call dic.Remove(Empty)
Set ToDictionaryArrayByArray2D_OK = dic
End Function
Sub test_toDic()
Dim dic As Dictionary
Set dic = ToDictionaryArrayByArray2D_OK([A1:C4].Value)
Stop
Set dic = ToDictionaryArrayByArray2D_NG([A1:C4].Value)
Stop
End Sub
Sub Dictionary原理の説明用()
Dim dic As Dictionary
Set dic = New Dictionary
dic.Add "n", 1
dic("n") = 2 '直接代入なので効果あり
Dim n As Long
n = 3
dic("n") = n '直接代入なので効果あり
n = 4 '参照型ではないので当然dicには効果なし
Dim v As Variant
dic.Add "v", v
v = "vvv" '参照型ではないので当然dicには効果なし
Dim c As New Collection
dic.Add "c", c
c.Add "cllAdd" '参照型なのでdicにも効果あり
Dim a(1 To 2) As Variant
dic.Add "a", a
a(1) = 1 '参照型ではないので当然dicには効果なし
a(2) = 2 '参照型ではないので当然dicには効果なし
dic("a")(1) = 111 'エラーは出ないのになぜか代入されない
dic("a")(2) = 222 'エラーは出ないのになぜか代入されない
Dim vvvvv
vvvvv = dic("a")
vvvvv(1) = 11111
vvvvv(2) = 22222
dic("a") = vvvvv '直接代入なので効果あり
End Sub
@KotorinChunChun
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment