将数组返回到单元格

时间:2016-12-22 06:06:24

标签: arrays excel-vba vba excel

在下面的脚本中,该函数仅返回6的最终值作为返回值。任何人都可以帮我恢复中间值3,4,5,6。

Function test_array() As Variant

Dim test() As Integer
Dim i As Integer

For i = 0 To 3
   ReDim Preserve test(i)
    test(i) = 3 + i
    test_array = test(i)  
Next i

End Function

3 个答案:

答案 0 :(得分:1)

对于输出为3,4,5,6,您需要创建一个字符串数组,并且可以使用Join函数来获得所需的输出。

代码的PFB。我希望这会有所帮助。

Function test_array() As String

Dim test() As String
Dim i As Integer

For i = 0 To 3
   ReDim Preserve test(i)
    test(i) = 3 + i
Next i

test_array = Join(test, ",")

End Function

答案 1 :(得分:0)

要返回整个数组,您只需将行test_array = test(i)修改为test_array = test,并将其置于For循环之外。原因是一旦test数组完全填充在For循环中,您将其内容复制到test_array,并将其返回给调用过程。

我添加了一个简短的测试函数过程,只是为了显示所有数组结果都返回给调用过程。

功能 test_array 代码

Function test_array() As Variant

Dim test() As Integer
Dim i As Integer

For i = 0 To 3
    ReDim Preserve test(i)
    test(i) = 3 + i
Next i
test_array = test

End Function

Sub Test_Func 代码

Sub Test_Func()

Dim myArr() As Integer
Dim i As Integer

myArr = test_array

For i = LBound(myArr) To UBound(myArr)
    MsgBox "Array element " & i & " value is " & myArr(i)
Next i

End Sub

编辑1 :将数组中的所有元素返回到单元格(作为String):

Function test_array() As String

Dim test() As Integer
Dim testStr As String
Dim i As Integer

For i = 0 To 3
    ReDim Preserve test(i)
    test(i) = 3 + i
    If testStr = "" Then
        testStr = test(i)
    Else
        testStr = testStr & "," & test(i)
    End If
Next i
test_array = testStr

End Function

答案 2 :(得分:0)

    'Little modification to your code will return all value as comma separated value like "3,4,5,6" in a cell
    Function test_array() As Variant
    Dim test() As Integer
    Dim i As Integer
    Dim ret As String
    For i = 0 To 3
       ReDim Preserve test(i)
        test(i) = 3 + i
        ret = ret & "," & test(i)
    Next i
    test_array = ret
    End Function

    Sub test1()
    Cells(1, 1) = test_array()
    'This must produce string "3,4,5,6" in cell A1 of active excel sheet
    End Sub