![](/img/trans.png)
[英]VBA Excel Printing data into Immediate Window about a range data to test understanding
[英]printing a collection item to immediate window in excel vba
我想知道如何將集合中的項目打印到excel VBA的直接窗口中? 我想為每個集合項都具有一個集合,或者為每個集合項都具有一個數組,而從中提取信息更容易。 這是我正在談論的一些示例代碼
Sub test()
Dim c As Collection
Dim a As Collection
Set a = New Collection
For i = 1 To 10
Set c = New Collection
c.Add Array("value1", "value2", "value3","valvue4, "value5"), "key1"
c.Add "value2", "key2"
c.Add "value3", "key3"
c.Add "value4, "key4"
c.Add "value5", "key5"
a.Add c, c.Item(1)
'lets say I wanted to print value4 or value1 from the 1st item
Debug.Print a.Item(1(2))
Next i
End Sub
這似乎可行:
Sub ytrewq()
Dim c As Collection
Set c = New Collection
c.Add "x", CStr("x")
c.Add "y", CStr("y")
c.Add "z", CStr("z")
i = 2
MsgBox c.Item(i)
Debug.Print c.Item(i)
End Sub
要添加到@Gary的學生答案中,您不能使用整數作為集合的鍵。 因此,您可以使用Cstr函數將其轉換為字符串,也可以使用字典。 如果決定使用字典,請確保啟用Microsoft Scripting Runtime(在工具->引用下)。 我在下面添加了一些示例。
Sub collExample()
Dim i As Integer
Dim c As Collection
Set c = New Collection
For i = 1 To 10
c.Add 2 * i, CStr(i)
Next i
'keys cant be integers
'see https://msdn.microsoft.com/en-us/library/vstudio/f26wd2e5(v=vs.100).aspx
For i = 1 To 10
c.Item (i)
Next i
End Sub
Sub dictExample()
Dim d As New Dictionary
Dim i As Integer
For i = 1 To 10
d(i) = 2 * i
Next i
Dim k As Variant
For Each k In d
Debug.Print k, d(k)
Next k
Dim coll As New Collection
coll.Add "value1"
coll.Add "value2"
coll.Add "value3"
Set d("list") = coll
Dim newCol As Collection
Set newCol = d("list")
Dim v As Variant
For Each v In newCol
Debug.Print v
Next v
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.