简体   繁体   中英

How do I return an array from a vba function in Excel?

I would like to return an array of unknown size from a vba function. I have little experience with vba.

I googled this question and found this page: Returning Arrays From VBA User Defined Functions .

It gives the following example for a function that will return an array:

Function Test() As Variant
    Dim V() As Variant
    Dim N As Long
    Dim R As Long
    Dim C As Long
    ReDim V(1 To 3, 1 To 4)
    For R = 1 To 3
        For C = 1 To 4
            N = N + 1
            V(R, C) = N
        Next C
    Next R
    Test = V
End Function

So I typed Alt+F11 , created a new module and entered this function. Then, in my workbook, I created a new sheet, typed =Test() in a cell and hit Ctrl+Shift+Enter , and a 1 appeared in a single cell.

What am I doing wrong? According to the site, the output of this should be

an array with 3 rows and 4 columns that contains the integers from 1 to 12.

First hi-light A1 through D3 . Then enter:

=Test()

as an array formula :

在此处输入图片说明

Array formulas must be entered with Ctrl + Shift + Enter rather than just the Enter key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM