0

the main goal is copying the worksheets name to an array, and array passes from function to main code to be able to track new added worksheets name to the array and work with them accordingly

Public Function CountWorksheets() As String
Dim i, size As Integer
Dim Arr() As String
size = Worksheets.Count
ReDim Arr(size)
For i = 1 To Worksheets.Count
    Arr(i) = Worksheets(i).Name
Next i
CountWorksheets = Arr
End Function



Private Sub RunLoc_Click()
Dim ar() As String
ReDim ar(Worksheets.Count)
j = 1
If Not IsEmpty(Location.Value) Then
    RunLoc.Enabled = True
    For i = 1 To Worksheets.Count
        If Worksheets(i).Name = Location.Value Then
            Worksheets(i).Select
            Range("a1").Select
        End If
    Next i
    ar = CountWorksheets()
End If
TextBox1.Value = Location.Value

End Sub

I expect to have the Arr and CountWorksheets with the same array recorded in both in function, and when CountWorksheets is called, the total of the array is copied to the new one which is named ar.

2
  • What's wrong with your code? Commented Jan 9, 2019 at 14:43
  • ar = CountWorksheets() -> Error:Cant assign to array Commented Jan 9, 2019 at 14:48

1 Answer 1

1

You need to return a variant or String(). Also, adjust your array to start at 1

ReDim Arr(1 To size)

Otherwise you will have an empty position at start.Or, do the necessary substractions to start at 0.

Option Explicit

Public Function CountWorksheets() As Variant
    Dim i, size As Integer
    Dim Arr() As String
    size = Worksheets.Count
    ReDim Arr(1 To size)
    For i = 1 To Worksheets.Count
        Arr(i) = Worksheets(i).NAME
    Next i
    CountWorksheets = Arr
End Function

Private Sub RunLoc_Click()
    Dim ar() As String
    ReDim ar(Worksheets.Count)

    ar = CountWorksheets
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.