VBA返回一个数组

时间:2014-05-31 09:45:01

标签: excel vba

我有以下代码,用于获取工作表名称并将它们放入数组中:

Function GetSheetNames(WBook) As String()
    Dim TempArray() As String        
    NoSheets = WBook.Sheets.Count
    ReDim TempArray(1 To NoSheets)
    For i = 1 To NoSheets
        TempArray(i) = WBook.Sheets(i).Name
    Next i        
    GetSheetNames = TempArray
End Function

我试图重构代码以摆脱TempArray变量:

Function GetSheetNames(WBook) As String()    
    NoSheets = WBook.Sheets.Count
    ReDim GetSheetNames(1 To NoSheets)
    For i = 1 To NoSheets
        GetSheetNames(i) = WBook.Sheets(i).Name
    Next i
End Function

但是它会返回错误。在VBA中这样的事情是否可能?我是否总是需要一个函数内部的临时局部变量,该函数最后被分配给函数名以便返回它?

1 个答案:

答案 0 :(得分:2)

你需要临时数组:

Function GetSheetNames(WBook As Workbook)
    NoSheets = WBook.Sheets.Count
    ReDim ary(1 To NoSheets)
    For i = 1 To NoSheets
        ary(i) = WBook.Sheets(i).Name
    Next i
    GetSheetNames = ary
End Function

Sub MAIN()
    Dim arry
    arry = GetSheetNames(ActiveWorkbook)
    For Each a In arry
        MsgBox a
    Next a
End Sub