数组到Excel范围

时间:2014-07-10 19:55:41

标签: excel vba excel-vba

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

我试图将数组输出到公式所在的最大行数。我正在使用Microsoft Scripting Library作为字典,如果这很重要的话。   使用excel中的数组公式(CTRL + Shift + Enter),如何将数组的大小调整到放置公式的范围,然后将数组放在单元格中?   我希望单元格上的公式为= test(" G1:J20"),公式将放在单元格A1:B20中。

Code:
    Function test(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 个答案:

答案 0 :(得分:1)

要读取和写入数组到单元格,您需要一个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

答案 1 :(得分:0)

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

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