我是VBA的新手,并尝试通过数组UDF将数组写入excel范围 .
我试图将数组输出到公式所在的最大行数 . 我正在使用Microsoft Scripting Library作为字典,如果这很重要 . 使用excel中的数组公式(CTRL Shift Enter),如何将数组的大小调整为放置公式的范围,然后将数组放入单元格中?我希望细胞上的公式为= test(“G1:J20”),公式将放在单元格A1:B20中 .
代码:功能测试(ByVal inputRange As Range)As Variant Dim Cell As Variant Dim D As Dictionary Dim Arr()As Variant Dim i As Long Set D = New Dictionary
' Remove duplicates
For Each Cell In inputRange
If D.Exists(CStr(Cell.Value)) = False Then
D.Add CStr(Cell.Value), 1
Else
D.Exists (Cell.Value)
D.Item(Cell.Value) = D.Item(Cell.Value) + 1
End If
Next
D.Remove vbNullString
Redim Arr(0 To Application.Max(D.Count, Application.Caller.Cells.Count))
'Fill the array with the keys from the Dictionary
For i = 0 To D.Count - 1
Arr(i) = D.Keys(i)
Next i
test = Application.Transpose(Arr)
End Function
2 回答
要读取和写入数组到单元格,您需要一个2D数组 . 例如:
或者只是读取值
这是一个将数组放入工作表范围的方法,这是你的意思吗?
但是,由于您已经遍历字典中的值,为什么不直接将值写入工作表?您可以通过交换行和列索引来模仿转置