数组到Excel范围

我是VBA新手,并尝试通过数组UDF将数组写入excel范围。

我正在尝试将数组输出到公式所在行的最大数量。如果有问题,我正在使用Microsoft Scripting Library作为字典。 在excel中的数组公式(CTRL + SHIFT + ENTER)中,如何将数组的大小调整到公式所在的范围,然后将数组放入单元格中? 我希望单元格上的公式为= test(“G1:J20”),公式将放置在单元格A1:B20中。

代码:函数testing(ByVal inputRange作为范围)作为变体昏暗的单元格作为变体昏暗的D作为字典昏暗的Arr()作为变体昏暗我只要设置D =新词典

' 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 

要读取数组并将其写入单元格,您需要一个2D数组。 例如:

 Dim data() as Variant, N as Integer, M as Integer ' Say you want a 100×50 array N = 100 : M = 50 ReDim data(1 to N, 1 to M) ' Fill data() Range("A1").Resize(N,M).Value = data 

或者只是读取值

 Dim data() as Variant, N as Integer, M as Integer, i as Integer, j as Integer data = Range("A1:AX100").Value N = UBOUND(data,1) : M = UBOUND(data,2) For i = 1 to N For j = 1 to M Debug.Print(data(i,j)) Next j Next i 

这是一个将数组放入工作表范围的方法,这是您的意思吗?

 Sub test() Dim v(0 To 2, 0 To 2) As Variant Dim r As Range 'fill the array with values populate v 'range must be same dimensions as array, in this case 3x3 Set r = ActiveSheet.Range("A1:C3") 'this simply puts array into range values r.Value2 = v End Sub Function populate(v As Variant) For i = 0 To 2 For j = 0 To 2 v(j, i) = i * j * j - i + 2 Next j Next i End Function 

但是,由于您已经在循环查看值的字典,为什么不直接将值写入工作表呢? 您可以通过交换行和列索引来模仿转置

 Sub test() Dim dict As Dictionary Set dict = New Dictionary 'fill dictionary with values populate dict 'loop through dictionary, and add items to worksheet For i = 0 To dict.Count - 1 ActiveSheet.Cells(1, i + 1).Value = dict.Keys(i) ActiveSheet.Cells(2, i + 1).Value = dict.Items(i) Next i End Sub Function populate(dict As Dictionary) dict.Add "help", "me" dict.Add "I'm", "lost" dict.Add "everything", "1" dict.Add "or", "0" End Function