0

In the code below, we can put Sheet1 - Sheet4 in selection mode and copy. But the point here is that the number of Sheets varies. Each time the file is changed, the number of Sheets is low or high. I just want to copy Sheet1 .... n, not all Sheets. (Every Sheet with the name of the "Sheet". How can this code be corrected for this issue?

Worksheets(Array("Sheet1", "Sheet2", "Sheet4")).Copy
3
  • What is your goal ?? Do you want to copy ALL the sheets in a workbook ??? Commented Oct 28, 2018 at 16:11
  • Explain your goal... Commented Oct 28, 2018 at 16:12
  • The text of the question was corrected. I hope you understand what I mean. Commented Oct 28, 2018 at 16:21

1 Answer 1

3
Sub m()
    Dim nSht As Long
    ReDim shts(1 To Worksheets.Count) As String

    Dim sht As Worksheet
    For Each sht In Worksheets
        If sht.Name Like "Sheet*" Then
            nSht = nSht + 1
            shts(nSht) = sht.Name
        End If
    Next

    If nSht > 0 Then
        ReDim Preserve shts(1 To nSht)
        Worksheets(shts).Copy
    End If

just for the record, here's the first solution spoiling

Dim sht As Worksheet

For Each sht In Worksheets
    If sht.Name Like "Sheet*" Then
        If Not ActiveSheet.Name Like "Sheet*" Then sht.Activate
        sht.Select False
    End If
Next
ThisWorkbook.Windows(1).SelectedSheets.Copy
Sign up to request clarification or add additional context in comments.

4 Comments

I tested your code. If you are on sheets other than Sheet (e.g. S), then all the sheets are copied. Please try and report the result.
Actually there's the behavior you reported. It could be managed but it'd spoil the first solution "style". So see edited code for a more conventional solution
you are welcome. you can see edited answer for the first solution amended to cope with the case you noticed
@DisplayName nice solution. I forgot about Worksheet.Select False. I miss read the OP's post.

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.