Excel 2010 VBA: How to store an array of worksheets as a variable?

前端 未结 5 818
忘掉有多难
忘掉有多难 2021-01-03 10:37

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.Shee         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-03 11:07

    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 :)

提交回复
热议问题