有一个函数返回一个数组

时间:2013-11-28 21:20:20

标签: excel vba excel-vba excel-2010

我想创建一个执行某些检查的函数,并将一个数组返回给我的调用子。这个数组不能真正在sub中创建,然后传递给函数进行操作。 sub只调用必须创建数组的函数并将其返回给sub。这可能吗?

这是我的功能。第一行显然是不正确的,但这是我想要做的想法。

Function rMMopened(1 to 1000)() As Long

Dim r As Long, i As Long
Dim ttd As Worksheet
Dim lrttd As Long

Set ttd = Sheets("Tasks_to_do")

lrttd = ttd.Cells(Rows.count, 1).End(xlUp).Row
ReDim rMMopened(1 To lrttd)

i = 1    
For r = 2 To lrttd    
    If ttd.Cells(r, 10) = "Phase 2" Then        
        If InStr("MASTER", ttd.Cells(r, 4)) Then            
            rMMopened(i) = r
            i = i = 1                
        End If        
    End If        
Next

ReDim Preserve rMMopened(1 To (i - 1))    
End Function

由于

1 个答案:

答案 0 :(得分:2)

这个怎么样:

Function rMMopened() As Long()      ' *** changed

Dim Values() As Long                ' *** added
Dim r As Long, i As Long
Dim ttd As Worksheet
Dim lrttd As Long

Set ttd = Sheets("Tasks_to_do")

lrttd = ttd.Cells(Rows.Count, 1).End(xlUp).Row
ReDim Values(1 To lrttd)            ' *** changed

i = 1

For r = 2 To lrttd

    If ttd.Cells(r, 10) = "Phase 2" Then

        If InStr("MASTER", ttd.Cells(r, 4)) Then

            Values(i) = r           ' *** changed
            i = i = 1

        End If

    End If

Next

ReDim Preserve Values(1 To (i - 1)) ' *** changed
rMMopened = Values                  ' *** added

End Function