3

I am trying to have several arrays of my worksheets that I can call up in my code using.

ThisWorkbook.Sheets(Array("Sheet1", "Sheet3"))
ThisWorkbook.Sheets(Array("Sheet2", "Sheet5"))

I am wondering if there is anyway to set up a variable similar to the following:

Dim ArrayOne As String
Dim ArrayTwo As String

ArrayOne = ThisWorkbook.Sheets(Array("Sheet1", "Sheet3"))
ArrayTwo = ThisWorkbook.Sheets(Array("Sheet2", "Sheet5"))

ArrayOne 'Call this Array then save

Filename:="C:\Data\testfile.xls", FileFormat:= _
xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _,
CreateBackup:=False 

ArrayTwo 'Call this array then save

Filename:="C:\Data\testfile.xls", FileFormat:= _
xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _,
CreateBackup:=False 

Please let me know if you can help me!!

2
  • 1
    an array isnt of the type String, and wha tyou are referring to isnt the names but the sheets themselves (being Sheet objects), this does not compute indeed. Question is what you want stored or referenced, the names or the sheet-objects? Commented Jun 18, 2013 at 12:48
  • 1
    The sheet-objects themselves. I want to be able to save the worksheets I select within my code to be saved as a new file. Commented Jun 18, 2013 at 12:51

5 Answers 5

4

Try using the record macro functionality. It will allow you to select multiple sheets and then copy them into a new book. Next save that book and you are there. Now tinker with the code to get it to work specifically the way you want.

It will come down to:

ThisWorkbook.Sheets(Array("Sheet1", "Sheet3")).Copy
ActiveWorkbook.SaveAs ...

If you want to predefine the arrays, thats is easily done as well; those will just have to contain the names of the sheets. An Array can be created by using a Variable variable:

Dim ArrayOne as Variant
ArrayOne = Array("Sheet1", "Sheet3")

And use that in the .Sheets().Copy :

ThisWorkbook.Sheets(ArrayOne).Copy
Sign up to request clarification or add additional context in comments.

4 Comments

This was exactly what I wanted to know! Thank you so much K_B!!
K_B, I am having some issues with setting ArrayOne as a variable variable. I am getting an error that reads "User-Defined type not defined". Any ideas? Also, thanks for being patient with me - I know it is pretty obvious that I am new to this stuff.
Nevermind, I had to use "Variant" not "Variable"! Thank you again for the help!!
ah, stupid me, indeed so. I did some parts by heart, so it wasnt tested.
4

Here is an example of how arrays in VBA work:

Sub Example()
    Dim ArrayOne() As String
    Dim ArrayTwo() As String
    Dim ArrayThree As Variant
    Dim i As Long

    ReDim ArrayOne(1 To Sheets.Count)
    ReDim ArrayTwo(1 To 2)

    For i = 1 To Sheets.Count
        ArrayOne(i) = Sheets(i).Name
    Next

    ArrayTwo(1) = "Sheet1"
    ArrayTwo(2) = "Sheet2"

    ArrayThree = Array("Sheet1", "Sheet3")
End Sub

Now from what I understand you do not want to use arrays. You can reference worksheets in your workbook like this:

Sheets("SheetName") 'SheetName is the name of your sheet
Sheets(1)           '1 = sheet index

One way to copy sheets to a new workbook to be saved is:

Sub Example()
    Dim wkbk As Workbook

    ThisWorkbook.Sheets("Sheet1").Copy
    Set wkbk = ActiveWorkbook
    ThisWorkbook.Sheets("Sheet3").Copy After:=wkbk.Sheets(wkbk.Sheets.Count)

    wkbk.SaveAs FileName:="C:\New Excel Book.xlsx", _
                FileFormat:=xlOpenXMLWorkbook
    wkbk.Close
End Sub

1 Comment

Thank you for the explanation! This really helped with my understanding of vba! However, K_B's answer is just as workable for me so I will be sticking with his answer.
2

I had a similar problem trying to create a dynamic array (not knowing how many sheets there was for me to deal with). I simply used this:

Sub copyArrayOfSheets()

Dim loopArray() As Variant

ReDim Preserve loopArray(1 To 1)
loopArray(1) = "Sheet1" ' a Sheet I know I need to export

j = 1
For Each loopSheet In ThisWorkbook.Sheets
    If loopSheet.Name <> "Sheet1" Then
        theName = loopSheet.Name
        j = j + 1
        ReDim Preserve loopArray(1 To j)
        loopArray(j) = theName ' Assign the name of the sheets to j-th position of loopArray() 
    End If
Next loopSheet

Sheets(loopArray()).Copy

Set newBook = ActiveWorkbook    
newBook.Activate

End Sub

Hope this helps in any way...

1 Comment

This was helpful for me as I seem to be adding more reports over time and this makes it easy to add logic to expand the array. I prefer to increment my counters at the end though so I initialized j as 2 instead of 1.
0

Following Arthur's solution (last comment), I had a similar problem (thus reached this post) : I was trying to create a dynamic array, which would save a series of sheets within a Workbook in an array and then perform specific actions with that array.

What is different is that, the user defines the sheets' names within a range (column) in excel (they represent scenarios for another macro), however this range may be expanded or shortened.

I use 2 arrays, where i run the loop in the first and save the extension each time to the other array (for transparency reasons). Code:

Sub testArray()
    Dim a, b As Integer
    scenarios_number = Sheets(sheet1).[c1] - 1 ' (this is where i put the # of scenarios / sheets (-1 is used as i want the array to start from 0))
    a = 0
    Dim Scenarios_array, dimension_array() As Variant
    ReDim Scenarios_array(0 To scenarios_number) '(resize array to match the #'s of scenarios)
    ReDim dimension_array(0 To a)
    For a = 0 To scenarios_number
    Scenarios_array(a) = Range("c8").Offset(a, 0).Value '(this is where my scenarios' names start within sheet1 -- using offset for the loop -- this is why i use -1 above as i want a to start @ 0)
    ReDim Preserve dimension_array(0 To a) ' (expand dimension of 2nd array)
    dimension_array(a) = Scenarios_array(a) ' (save the value in the second array, expaning its dimensions)
    Next
    MsgBox "Get Ready"
    Sheets(dimension_array()).Select
    ActiveWindow.SelectedSheets.Delete
End Sub

Hope that helps :)

Comments

0

I also was trying to do this but I found another way

What i was trying to accomplish was that I have a workbook with multiple sheets and gave them a name. I wanted to select a few sheets and exclude a few sheets that needed to be exported to a different excel file.

Here is (after a lot of searching and trying) my code

Dustin

Dim ii As Integer 'Counter of worksheets
Dim namefile as string 'Variable for name of the new file
namefile = "NameOfNewFile.xlsx" 'Name of new file

For ii = 1 To ThisWorkbook.Sheets.Count 'Counts from 1 to last sheetnumber
    If Sheets(ii).Name <> "Namesheet1" Then If Sheets(ii).Name <> "Namesheet2" Then Sheets(ii).Select Replace:=False 
    'NameSheet1 and NameSheet2 are being exluded from the new file
Next ii

ActiveWindow.SelectedSheets.Copy 'Copies the selected files

Set NewWb = ActiveWorkbook
NewWb.SaveAs Filename:= _
"C:\Users\" & Environ("UserName") & "\Desktop\" & namefile, FileFormat:=xlOpenXMLWorkbook 
'Saves as xlsx file to desktop
NewWb.Close 'Closes the new file
Set NewWb = Nothing 'Clear NewWb to reduce memory usage

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.