VBA - Using an array to copy a dynamic range of sheets to a new book

BigShango

Board Regular
Joined
May 8, 2014
Messages
106
Hi,

Having a bit of bother getting my head around using arrays.

I have a list of names in Column A of a sheet. I need to copy any sheets in the workbook that match those names to a new workbook.

So, for example, Column A on Sheets("Names") is
Steve Wilson
John Jackson
Percy Peterson
Rab Rabson

In the workbook there are sheets named Percy Peterson and Rab Rabson, so I need them copied to a new workbook, there are not sheets names Steve Wilson or John Jackson.

What I thought I needed to do is create an array for the list of names (NamesArray) then search each one across the whole workbook, if a sheet matches that name add it to another array (CopyArray) but I just can't seem to get it. I really struggle with arrays tbh.

This is also part of a much larger process.
 

Excel Facts

Which came first: VisiCalc or Lotus 1-2-3?
Dan Bricklin and Bob Frankston debuted VisiCalc in 1979 as a Visible Calculator. Lotus 1-2-3 debuted in the early 1980's, from Mitch Kapor.
Try this:

Code:
Dim NameArray() As String
Sub MoveBookNames()
    Dim ws As Worksheet
    Dim i As Integer
    i = 1
    ReDim Preserve NameArray(0 To 0) As String
    Do Until Sheets("Names").Cells(i, 1) = ""
        For Each ws In ThisWorkbook.Worksheets
            If ws.Name = Sheets("Names").Cells(i, 1) Then
                ReDim Preserve NameArray(0 To UBound(NameArray) + 1)
                NameArray(UBound(NameArray) - 1) = ws.Name
            End If
        
        
        Next
    
    
        i = i + 1
    Loop
    ReDim Preserve NameArray(0 To UBound(NameArray) - 1)
    ThisWorkbook.Sheets(NameArray).Copy

End Sub
 
Upvote 0

Forum statistics

Threads
1,223,236
Messages
6,170,917
Members
452,366
Latest member
TePunaBloke

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top