Excel VBA - 水平转置数组

时间:2017-09-25 10:55:08

标签: arrays excel-vba paste vba excel

我有一个数组(dict1),我想使用以下代码从单元格T1-Z1粘贴

With Sheets("Raw_Data")
  .Range(.Cells(1, 20), .Cells(1, 26)).Resize(dict1.Count).Value = Application.Transpose(dict1.keys)
End With

但是当我使用它时,它会从T1-T7中粘贴数组中的值,然后从列T-Z复制它。无论如何我可以改变它,所以它将数组转换为水平移动

1 个答案:

答案 0 :(得分:2)

而不是

.Range(.Cells(1, 20), .Cells(1, 26)).Resize(dict1.Count).Value = Application.Transpose(dict1.keys)

使用

.Range("T1").Resize(1, UBound(Application.Transpose(dict1.keys))) = dict1.keys

尝试以下代码

Sub Demo()
    Dim dict1 As Object
    Set dict1 = CreateObject("Scripting.Dictionary")

    'assume following are the disctionary items
    dict1.Add "Aaa", 1
    dict1.Add "Bbb", 2
    dict1.Add "Ccc", 3
    dict1.Add "Ddd", 4
    dict1.Add "Eee", 5
    dict1.Add "Fff", 6
    dict1.Add "Ggg", 7

    'output dictionary horizontally
    With Sheets("Raw_Data")
        .Range("T1").Resize(1, UBound(Application.Transpose(dict1.Keys))) = dict1.Keys
    End With
End Sub

这反映在下面的图像中。

enter image description here