excel 将数组字典的内容打印到工作表

hgtggwj0  于 2023-01-06  发布在  其他
关注(0)|答案(2)|浏览(129)

我正尝试一下子将数组字典的内容打印到Excel工作表上。
字典的结构可能是这样的:第一个月
其中employee是一个包含三个值的数组,例如name、姓氏和年龄。
只要这些项是单值的,我就可以使用如下语句打印字典

Cells(1, 1).Resize(dict.Count, 1).Value2 = Application.Transpose(dict.Keys)
Cells(1, 2).Resize(dict.Count, 1).Value2 = Application.Transpose(dict.Items)

当我把数组作为项时,我无法得到一个解.

2wnc66cl

2wnc66cl1#

出现错误。dict.Keys -它是键的数组!不能将单元格值设置为数组。需要设置字符串变量并收集其中的所有键

Dim str1 as String
Dim str2 as String
For i=1 to count 'qty of elements in dictionary
str1=str1 & dict.Keys()(i) 
str2=str2 & dict.Items()(i) 
Next i

这里是关于字典的文章的链接
http://www.snb-vba.eu/VBA_Dictionary_en.html

bn31dyow

bn31dyow2#

通过循环,你可以做这样的事情-应该还是很快的。

Sub DictOutput()
    
    Dim dict As Object, i As Long, r As Long, cols As Long, col As Long, arr, data, k
    Set dict = CreateObject("scripting.dictionary")
    
    'load some test data
    For i = 1 To 100
        dict.Add "Key_" & Format(i, "000"), Split("A,B,C,D", ",")
    Next i
    
    arr = dict.Items()(0)                        'get the first value
    cols = 1 + (UBound(arr) - LBound(arr))       'number of items in array (assumed all the same size)
    ReDim data(1 To dict.Count, 1 To (1 + cols)) 'size the output array
    r = 0
    
    For Each k In dict 'loop and fill the output array
        r = r + 1
        data(r, 1) = k
        arr = dict(k)
        i = 2
        For col = LBound(arr) To UBound(arr) 'loop array and populate output row
            data(r, i) = arr(col)
            i = i + 1
        Next col
    Next k
    
    'put the data on the sheet
    ActiveSheet.Range("A1").Resize(UBound(data, 1), UBound(data, 2)).Value = data
End Sub

相关问题