1

I have the following code which is meant to obtain the sheet names and put them into an array:

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

I tried to refactor the code to get rid of the TempArray variable:

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

However it returns an error. Is such thing even possible in VBA? Do I always need a temporary local variable inside a function which at the end gets assigned to the function name in order to return it?

1 Answer 1

2

You need the temp array:

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.